.NET Core 基于Websocket的在线聊天室实现(2)

public class WebsocketClientCollection { private static List<WebsocketClient> _clients = new List<WebsocketClient>(); public static void Add(WebsocketClient client) { _clients.Add(client); } public static void Remove(WebsocketClient client) { _clients.Remove(client); } public static WebsocketClient Get(string clientId) { var client = _clients.FirstOrDefault(c=>c.Id == clientId); return client; } public static List<WebsocketClient> GetRoomClients(string roomNo) { var client = _clients.Where(c => c.RoomNo == roomNo); return client.ToList(); } }

在Startup中使用中间件

有了上面的中间件,我们需要use一下。

app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(60), ReceiveBufferSize = 1* 1024 }); app.UseMiddleware<WebsocketHandlerMiddleware>();

到此我们的服务端基本完成了,下面进行客户端html跟JavaScript的编写。

编写客户端界面

修改index.cshtml来实现一个简单的聊天室ui。

<div> room no: <input type="text" value="8888"/> <button>join room</button> <button>leave room</button> </div> <div> nick name: <input type="text" value="batman" /> </div> <div> <textarea></textarea> <div> <input type="text" value="" /> <button>send</button> </div> </div>

使用JavaScript来处理websocket链接及消息

现代浏览器已经都支持websocket协议,JavaScript运行时内置了WebSocket类,我们仅仅需要new一个Websocket对象出来就可以对websocket进行操作。

var server = 'ws://localhost:5000'; //如果开启了https则这里是wss var WEB_SOCKET = new WebSocket(server + '/ws'); WEB_SOCKET.onopen = function (evt) { console.log('Connection open ...'); $('#msgList').val('websocket connection opened .'); }; WEB_SOCKET.onmessage = function (evt) { console.log('Received Message: ' + evt.data); if (evt.data) { var content = $('#msgList').val(); content = content + '\r\n' + evt.data; $('#msgList').val(content); } }; WEB_SOCKET.onclose = function (evt) { console.log('Connection closed.'); }; $('#btnJoin').on('click', function () { var roomNo = $('#txtRoomNo').val(); var nick = $('#txtNickName').val(); if (roomNo) { var msg = { action: 'join', msg: roomNo, nick: nick }; WEB_SOCKET.send(JSON.stringify(msg)); } }); $('#btnSend').on('click', function () { var message = $('#txtMsg').val(); var nick = $('#txtNickName').val(); if (message) { WEB_SOCKET.send(JSON.stringify({ action: 'send_to_room', msg: message, nick: nick })); } }); $('#btnLeave').on('click', function () { var nick = $('#txtNickName').val(); var msg = { action: 'leave', msg: '', nick: nick }; WEB_SOCKET.send(JSON.stringify(msg)); });

运行

至此我们的聊天室已经搭建完成了,运行一下看看效果。我们启动两个页面,进行聊天。
可以看到我们的消息被实时的转发出去了,good job !

.NET Core 基于Websocket的在线聊天室实现


.NET Core 基于Websocket的在线聊天室实现

源码

源码已上传github
CoreWebsocketChatRoom

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/psdxd.html