标签:服务端 message 没有 eve 代码 hat utc start ace
原文:ASP.NET Core 2.2 基础知识(十七) SignalR 一个极其简陋的聊天室这个例子只是在官方的例子上加了 Group 的用法而已,主要是官方给的 Group 的例子就两行代码,看不出效果.
"use strict"; //创建一个连接 var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build(); //定义客户端的 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); }); //给"Send Message"按钮添加点击事件 document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; //调用服务端的 SendMessage 方法 connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); //给"进入聊天室"按钮添加点击事件 document.getElementById("goChatRoom").addEventListener("click", function () { goChatRoom();//开启连接 document.getElementById("outChatRoom").style.display = "block"; this.style.display = "none"; }); //给"退出聊天室"按钮添加点击事件 document.getElementById("outChatRoom").addEventListener("click", function () { outChatRoom();//关闭连接 this.style.display = "none"; document.getElementById("goChatRoom").style.display = "block"; }); //开启连接 function goChatRoom() { connection.start().catch(function (err) { return console.error(err.toString()); }); } //关闭连接 function outChatRoom() { connection.stop(); }
public interface IChatClient { //就算是这种强类型方式,客户端定义的方法名也必须和这个方法名一样,包括签名. Task ReceiveMessage(string user, string message); } public class StronglyTypedChatHub : Hub<IChatClient> { public async Task SendMessage(string user, string message) { //向所有连接的客户端中,在 "room" 小组的客户端发送消息 await Clients.Group("room").ReceiveMessage(user, message); } public override async Task OnConnectedAsync() { //当客户端连接上后,将其归属到 "room" 小组. await Groups.AddToGroupAsync(Context.ConnectionId, "room"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception exception) { //当客户端断开连接后,将其从 "room" 小组移除,一定要移除!不然会发送多条消息!!!! await Groups.RemoveFromGroupAsync(Context.ConnectionId, "room"); await base.OnDisconnectedAsync(exception); } }
public void ConfigureServices(IServiceCollection services) { ...... services.AddSignalR(); ...... }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ...... app.UseSignalR(routes => { routes.MapHub<StronglyTypedChatHub>("/chatHub"); }); app.UseMvc(); }
ASP.NET Core 2.2 基础知识(十七) SignalR 一个极其简陋的聊天室
标签:服务端 message 没有 eve 代码 hat utc start ace
原文地址:https://www.cnblogs.com/lonelyxmas/p/10249224.html