SignalR 框架
关键文件
客户端操作文件
"use strict"; //初始化连接 var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub", { accessTokenFactory: () => "" }).build(); //禁用发送按钮,直到建立连接 document.getElementById("sendButton").disabled = true; //接收事件 connection.on("ReceiveMessage1", 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.on("over", function (message) { var msg = message + "结束"; var li = document.createElement("li"); li.textContent = msg; document.getElementById("messagesList").appendChild(li); document.getElementById("sendButton").disabled = true; }); //建立连接,并启用发送按钮 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; //执行方法SendMessage1 connection.invoke("SendMessage1", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); });
服务端操作文件
public class ChatHub : Hub { public async Task SendMessage1(string user, string message) { var abc = Context; if (message == "over") { await Clients.All.SendAsync("over", "完成"); //return await Task.CompletedTask; return; } message += ",ok"; //发送到客户端,接收事件 //await Clients.All.SendAsync("ReceiveMessage1", user, message); //向特定用户发送信息 //await Clients.User(user).SendAsync("ReceiveMessage1", user, message); await Clients.Group("SignalR Users").SendAsync("ReceiveMessage1", user, message); } public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); } }
配置:
//启用SignalR services.AddSignalR();
app.UseEndpoints(endpoints => { //设置Hub endpoints.MapHub<ChatHub>("/chatHub"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
网页端:
<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> <script src="~/js/signalr/dist/browser/signalr.js"></script> <script src="~/js/chat.js"></script>