利用SignalR实现聊天室(实战篇)
简易单网页聊天室:
1.添加SignalR插件包:
2.在项目下创建文件夹:MyHub
且创建类:MyHub
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 [HubName("myHub")] 2 public class MyHub : Hub 3 { 4 private IList<string> userList = UserInfo.userList; 5 // public readonly static Dictionary<string, string> _connections = new Dictionary<string, string>(); 6 // Is set via the constructor on each creation 7 private Broadcaster _broadcaster; 8 /// <summary> 9 10 /// 静态用户列表 11 12 /// </summary> 13 14 15 16 public MyHub() : this(Broadcaster.Instance) 17 { 18 19 } 20 21 public MyHub(Broadcaster broadcaster) 22 { 23 _broadcaster = broadcaster; 24 25 } 26 public void Send(string msg) 27 { 28 string name = "NiHao"; 29 Clients.All.SendMessage(name, msg); 30 } 31 //客户端连接上时,会进入到此方法中 32 public override Task OnConnected() 33 { 34 Trace.WriteLine("客户端连接成功"); 35 return base.OnConnected(); 36 } 37 38 39 public override Task OnReconnected() 40 { 41 Trace.WriteLine("客户端重连中"); 42 return base.OnReconnected(); 43 } 44 45 public override Task OnDisconnected(bool stopCalled) 46 { 47 return base.OnDisconnected(stopCalled); 48 } 49 public void SendLogin(string name) 50 { 51 52 if (!userList.Contains(name)) 53 { 54 55 userList.Add(name); 56 57 //这里便是将用户id和姓名联系起来 58 59 Connects._connections.Add(name, Context.ConnectionId); 60 } 61 else 62 { 63 //每次登陆id会发生变化 64 65 Connects._connections[name] = Context.ConnectionId; 66 67 } 68 UserInfo.userList = userList; 69 //新用户上线,服务器广播该用户名 70 71 // Clients.All.loginUser(userList); 72 73 } 74 75 private Random random = new Random(); 76 77 /// <summary> 78 /// 被动收发消息 79 /// </summary> 80 /// <param name="name1">消息发起者</param> 81 /// <param name="name2">消息接收者</param> 82 public void SendByGroup(string name1, string name2, string Msg) 83 { 84 JObject json = new JObject(); 85 //Client内为用户的id,是唯一的,SendMessage函数是前端函数,意思是服务器将该消息推送至前端 86 87 json.Add("A", random.Next(1000, 10000).ToString()); 88 json.Add("B", random.Next(20).ToString()); 89 90 91 Clients.Client(Connects._connections[name2]).sendMessage_Persion("来自用户" + name1 + " " + DateTime.Now.ToString("yyyy/MM/ddhh:mm:ss") + "的消息推送!"+Msg); 92 // Clients.Client(Connects._connections[name2]).SendMessage(json); 93 94 } 95 } 96 97 98 /// <summary> 99 /// 数据广播器 100 /// </summary> 101 public class Broadcaster 102 { 103 private readonly static Lazy<Broadcaster> _instance = 104 new Lazy<Broadcaster>(() => new Broadcaster()); 105 106 private readonly IHubContext _hubContext; 107 108 private Timer _broadcastLoop; 109 110 public Broadcaster() 111 { 112 // 获取所有连接的句柄,方便后面进行消息广播 113 _hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 114 // Start the broadcast loop 115 _broadcastLoop = new Timer( 116 BroadcastShape, 117 null, 118 1000, 119 1000); 120 121 } 122 123 124 private Random random = new Random(); 125 126 127 private void BroadcastShape(object state) 128 { 129 // 定期执行的方法 130 //1.查找所有连接的PID与设备ID 131 //2.根据设备ID与PID查找所属的评分记录 132 //3.查找所有题目的判定条件 133 //4.对判定条件进行筛选 134 //5.合并判定条件 135 //6.对数据进行分发 136 //for (int i = 0; i < UserInfo.userList.Count; i++) 137 //{ 138 // IList<RebackModels> list = getDataServer.getSubmitLogInfo(UserInfo.userList[i].Split('_')[0], UserInfo.userList[i].Split('_')[1], UserInfo.userList[i].Split('_')[2]); 139 // _hubContext.Clients.Client(Connects._connections[UserInfo.userList[i]]).sendTest1(list); 140 //} 141 142 143 144 145 if (!Connects._connections.ContainsKey("wdd3"))//不存在 146 { 147 148 } 149 else//存在 150 { 151 _hubContext.Clients.Client(Connects._connections["wdd3"]).sendMessage123(random.Next(1000).ToString()); 152 } 153 _hubContext. Clients.All.sendMessage("当前随机数:"+random.Next(1000).ToString()); 154 155 // _hubContext.Clients.All(random.Next(1000).ToString()); 156 } 157 public static Broadcaster Instance 158 { 159 get 160 { 161 return _instance.Value; 162 } 163 } 164 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static class Connects 2 { 3 public readonly static Dictionary<string, string> _connections = new Dictionary<string, string>(); 4 } 5 public static class UserInfo 6 { 7 public static IList<string> userList = new List<string>(); 8 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <div id="test">这里即将显示服务器推送的数据</div> 2 <div id="test1">这里即将显示服务器推送的数据</div> 3 <div id="test2">这里即将显示服务器推送的数据</div> 4 <input type="hidden" id="displayname" /> 5 <div>发送人姓名<input type="text" style="width:200px" id="sendusername" /></div> 6 <div>发送内容:<input type="text" style="width:200px;height:100px" id="msgcontent" /></div> 7 <input id="send" type="button" value="发送" /> 8 <script src="~/Scripts/jquery-3.3.1.min.js"></script> 9 <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script> 10 <script src="~/signalr/hubs"></script> 11 <script> 12 $(function () { 13 var mypush = $.connection.myHub; 14 15 $('#displayname').val(prompt('请输入昵称:', '')) 16 17 mypush.client.sendMessage = function (message) { 18 $("#test").text(message); 19 console.log(message); 20 }; 21 mypush.client.sendMessage_Persion = function (message) { 22 $("#test2").text(message); 23 console.log(message); 24 }; 25 mypush.client.sendTest1 = function (message) { 26 $("#test1").text(message); 27 console.log(message); 28 setmsg(message); 29 }; 30 31 32 $.connection.hub.start().done(function () { 33 var username = $('#displayname').val(); 34 console.log(username); 35 mypush.server.sendLogin(username); 36 37 $('#send').click(function () { 38 39 var friend = $('#sendusername').val(); 40 var msgcontent = $("#msgcontent").val(); 41 //调用后端函数,发送指定消息 42 43 mypush.server.sendByGroup(username, friend, msgcontent); 44 45 }); 46 }); 47 }) 48 </script>