WebSocketForWebAPI:https://gitee.com/lycz/WebSocketForWebAPI
服务端发送消息,控制器代码
private readonly ClientWebSocket webSocket = new ClientWebSocket(); private readonly CancellationToken _cancellation = new CancellationToken(); [HttpPost] public async Task SendMsg(string msg) { await webSocket.ConnectAsync(new Uri("ws://localhost:56486/api/msg"), _cancellation); var sendBytes = Encoding.UTF8.GetBytes(msg);//发送的数据 var bsend = new ArraySegment<byte>(sendBytes); await webSocket.SendAsync(bsend, WebSocketMessageType.Binary, true, _cancellation); await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", _cancellation); webSocket.Dispose(); }
WebSocketForWebAPI代码
后台:MsgApiController.cs
[RoutePrefix("api/msg")] public class MsgApiController : ApiController { private static List<WebSocket> _sockets = new List<WebSocket>(); [Route] [HttpGet] public HttpResponseMessage Connect() { 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>(buffer.Array); foreach (var innerSocket in _sockets)//当接收到文本消息时,对当前服务器上所有web socket连接进行广播 { if (innerSocket != socket) { await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } } } } }
前端:
Msg.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> <script> var webSocket; function sendSocketMsg() { var msg = $("#msg").val(); webSocket.send(msg); showMsg(msg, "blue"); } function openSocket() { if (webSocket != null && typeof (webSocket) != "undefined") { closeSocket(); } webSocket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/api/msg"); webSocket.onopen = function () { showMsg("连接建立"); } webSocket.onerror = function () { showMsg("发生异常"); } webSocket.onmessage = function (event) { showMsg(event.data, "yellow"); } webSocket.onclose = function () { showMsg("连接关闭"); } } function closeSocket() { if (webSocket != null && typeof (webSocket) != "undefined") { webSocket.close(); } } function showMsg(msg, type) { if (type === null || typeof (type) === "undefined") type = "gray"; $("#show").append("<span class='" + type + "'>" + msg + "</span><br>"); } </script> <style> #show { border: 1px solid #ff6a00; padding: 10px; } .blue { border: 1px solid #0094ff; } .yellow { margin-left: 300px; border: 1px solid #b6ff00; } .gray { font-size: 10px; border: 1px solid #a9a9a9; } </style> </head> <body> <button onclick="openSocket()">建立连接</button> <button onclick="closeSocket()">断开连接</button> <hr /> <input type="text" id="msg" /> <button onclick="sendSocketMsg()">发送信息</button> <hr /> <div id="show"></div> </body> </html>