.net+H5 webSocket 實(shí)現(xiàn)聊天
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
Html代碼: <textarea rows="10" style="width:300px" id="contentArea"></textarea> <br/>姓名<input type="text" id="name" />內(nèi)容<input type="text" style="width:300px" id="content"/><button onclick="send()">發(fā)送</button> <script> var webSocket = new WebSocket("ws://localhost:9226/api/sys/test/GetConnect?nickName=admin" ); webSocket.onopen = function () { console.log("opened"); alert("已開啟,可聊天"); } webSocket.onerror = function () { console.log("web socket error"); } webSocket.onmessage = function (event) { console.log("onmessage"); console.log(event); document.getElementById("contentArea").value = document.getElementById("contentArea").value + "\r\n" + event.data; } webSocket.onclose = function () { console.log("closed"); } function send() { var value =document.getElementById("name").value+":"+ document.getElementById("content").value; webSocket.send(value); document.getElementById("contentArea").value = document.getElementById("contentArea").value + "\r\n" + value; document.getElementById("content").value = ""; } </script> .net 代碼 web.config處 在 system.web 下 httpRuntime加入 targetFramework="4.5" ApiControoler部分 private static List<WebSocket> _sockets = new List<WebSocket>(); [System.Web.Http.HttpGet] public HttpResponseMessage GetConnect(string nickName) { HttpContext.Current .AcceptWebSocketRequest( ProcessRequest); //在服務(wù)器端接受Web Socket請求,傳入的函數(shù)作為Web Socket的處理函數(shù),待Web Socket建立后該函數(shù)會被調(diào)用,在該函數(shù)中可以對Web Socket進(jìn)行消息收發(fā) return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //構(gòu)造同意切換至Web Socket的Response. } public async Task ProcessRequest(AspNetWebSocketContext context) { var socket = context.WebSocket; //傳入的context中有當(dāng)前的web socket對象 _sockets.Add(socket); //此處將web socket對象加入一個靜態(tài)列表中 //進(jìn)入一個無限循環(huán),當(dāng)web socket close是循環(huán)結(jié)束 while (true) { var buffer = new ArraySegment<byte>(new byte[1024]); var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None); //對web socket進(jìn)行異步接收數(shù)據(jù) if (receivedResult.MessageType == WebSocketMessageType.Close) { await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None); //如果client發(fā)起close請求,對client進(jìn)行ack _sockets.Remove(socket); break; } if (socket.State == System.Net.WebSockets.WebSocketState.Open) { string recvMsg = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count); var recvBytes = Encoding.UTF8.GetBytes(recvMsg); var sendBuffer = new ArraySegment<byte>(recvBytes); foreach (var innerSocket in _sockets) //當(dāng)接收到文本消息時,對當(dāng)前服務(wù)器上所有web socket連接進(jìn)行廣播 { if (innerSocket != socket) { await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } } } } 該文章在 2019/11/12 15:16:57 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |