SignalR基本使用
@adens
8/28/2020 8:15:57 AM
基本就是官方文档的直接使用
1.准备内容
1.1. ASP.NET Core 2.2及以上 已在框架中包含SignalR,无需安装额外的包
1.2.Javascript 前端页面需要下载@microsoft/signalr并在页面引用
区别于signalr这个是给.NET Framework 使用的.
2.开始构建
2.1. 新建一个类继承Hub,例如 RealplayHub
public class RealplayHub:Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
2.2.Startup里配置一下
ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
// other services
services.AddSignalR();
}
Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// other code
app.UseEndpoints(endpoints =>
{
// other endpoint
endpoints.MapHub<RealplayHub>("/realplayhub");
});
}
2.3. 前端页面内容
为了测试直接写在index里面
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">User</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">Message</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
<!--引入 javascript 客户端的signalr-->
<script src="~/lib/signalr/dist/browser/signalr.min.js"></script>
<!--接下来手动编写建立连接和收发消息的js-->
<script src="~/js/realplay.js"></script>
replay.js
"use strict";
//初始化连接
var connection = new signalR.HubConnectionBuilder().withUrl("/realplayhub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
//绑定接收消息的方法
//服务端发送消息到客户端的ReceiveMessage方法
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
//建立连接
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
var group = document.getElementById("groupInput").value;
//唤醒服务端方法//向服务端发送消息
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
从服务端主动发送消息给客户端
不可直接使用Clients.All.SendAsync();
必须注入IHubContext.集线器的上下文
使用IHubContext.Clients.All.SendAsync();
public IActionResult Broadcast()
{
_hubContext.Clients.All.SendAsync("ReceiveBroadcast", "Everyone Listening.");
}
```
js客户端需要监听 `ReceiveBroadcast`
```
connection.on("ReceiveBroadcast", function (message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var li = document.createElement("li");
li.textContent = msg ;
document.getElementById("messagesList").appendChild(li);
});
```
Last Modification : 8/28/2020 8:15:57 AM