.net+H5 webSocket 实现聊天
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
Html代码: <textarea rows="10" style="width:300px" id="contentArea"></textarea> <br/>姓名<input type="text" id="name" />内容<input type="text" style="width:300px" id="content"/><button onclick="send()">发送</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); //在服务器端接受Web Socket请求,传入的函数作为Web Socket的处理函数,待Web Socket建立后该函数会被调用,在该函数中可以对Web Socket进行消息收发 return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //构造同意切换至Web Socket的Response. } public async Task ProcessRequest(AspNetWebSocketContext context) { var socket = context.WebSocket; //传入的context中有当前的web socket对象 _sockets.Add(socket); //此处将web socket对象加入一个静态列表中 //进入一个无限循环,当web socket close是循环结束 while (true) { var buffer = new ArraySegment<byte>(new byte[1024]); var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None); //对web socket进行异步接收数据 if (receivedResult.MessageType == WebSocketMessageType.Close) { await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None); //如果client发起close请求,对client进行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) //当接收到文本消息时,对当前服务器上所有web socket连接进行广播 { if (innerSocket != socket) { await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } } } } 该文章在 2019/11/12 15:16:57 编辑过 |
关键字查询
相关文章
正在查询... |