今天就跟大家聊聊有关怎么在.NET Core 中利用Websocket实现一个在线聊天室功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
//客户端请求 GET / HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: example.com Origin: http://example.com Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ== Sec-WebSocket-Version: 13 //服务端响应 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s= Sec-WebSocket-Location: ws://example.com/
新建WebsocketHandlerMiddleware中间件
这个中间件就是我们管理websocket链接的入口,我们调用context.WebSockets.AcceptWebSocketAsync()方法把请求转换为websocket链接。
在Invoke方法内接收websocket链接
public async Task Invoke(HttpContext context) { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); string clientId = Guid.NewGuid().ToString(); ; var wsClient = new WebsocketClient { Id = clientId, WebSocket = webSocket }; try { await Handle(wsClient); } catch (Exception ex) { _logger.LogError(ex, "Echo websocket client {0} err .", clientId); await context.Response.WriteAsync("closed"); } } else { context.Response.StatusCode = 404; } } else { await _next(context); } }
在Hanle方法等待客户端的消息
private async Task Handle(WebsocketClient webSocket) { WebsocketClientCollection.Add(webSocket); _logger.LogInformation($"Websocket client added."); WebSocketReceiveResult result = null; do { var buffer = new byte[1024 * 1]; result = await webSocket.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Text && !result.CloseStatus.HasValue) { var msgString = Encoding.UTF8.GetString(buffer); _logger.LogInformation($"Websocket client ReceiveAsync message {msgString}."); var message = JsonConvert.DeserializeObject<Message>(msgString); message.SendClientId = webSocket.Id; MessageRoute(message); } } while (!result.CloseStatus.HasValue); WebsocketClientCollection.Remove(webSocket); _logger.LogInformation($"Websocket client closed."); }
在MessageRoute方法内对客户端的消息进行转发
对客户端的消息定义几个标准的action,对不同的action进行特定的处理,比如加入房间、离开房间、在房间内广播消息等。
private void MessageRoute(Message message) { var client = WebsocketClientCollection.Get(message.SendClientId); switch (message.action) { case "join": client.RoomNo = message.msg; client.SendMessageAsync($"{message.nick} join room {client.RoomNo} success ."); _logger.LogInformation($"Websocket client {message.SendClientId} join room {client.RoomNo}."); break; case "send_to_room": if (string.IsNullOrEmpty(client.RoomNo)) { break; } var clients = WebsocketClientCollection.GetRoomClients(client.RoomNo); clients.ForEach(c => { c.SendMessageAsync(message.nick + " : " + message.msg); }); _logger.LogInformation($"Websocket client {message.SendClientId} send message {message.msg} to room {client.RoomNo}"); break; case "leave": var roomNo = client.RoomNo; client.RoomNo = ""; client.SendMessageAsync($"{message.nick} leave room {roomNo} success ."); _logger.LogInformation($"Websocket client {message.SendClientId} leave room {roomNo}"); break; default: break; } }
新建WebsocketClientCollection管理类
这个类是个容器,用来存放所有的websocket链接,便于统一管理。
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" id="txtRoomNo" value="8888"/> <button id="btnJoin">join room</button> <button id="btnLeave">leave room</button> </div> <div > nick name: <input type="text" id="txtNickName" value="batman" /> </div> <div > <textarea id="msgList"></textarea> <div > <input type="text" id="txtMsg" value="" /> <button id="btnSend">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)); });
看完上述内容,你们对怎么在.NET Core 中利用Websocket实现一个在线聊天室功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。