您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在.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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。