WebSocketForWebAPI:https://gitee.com/lycz/WebSocketForWebAPI
The server sends a message, the controller code
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 Code
Background: MsgApiController.cs
[RoutePrefix ( " API / MSG " )] public class MsgApiController: ApiController { Private static List <a WebSocket> = _sockets new new List <a WebSocket> (); [the Route] [HttpGet] public HttpResponseMessage Connect () { HttpContext.Current.AcceptWebSocketRequest ( the ProcessRequest); // the server accepts requests Web Socket incoming Web Socket as a function of the handler until the Web Socket will be called after the establishment, may be of the messaging function in the Web Socket return Request.CreateResponse (HttpStatusCode.SwitchingProtocols); // configured to switch to the Web Socket consent of the Response. } public the async the Task the ProcessRequest (AspNetWebSocketContext context) { var Socket = context.WebSocket; // incoming current context there web socket objects _sockets.Add (Socket); // where the object is added to a static web socket list // into an infinite loop, when the loop end is a web socket close the while ( to true ) { var Buffer = new new ArraySegment < byte > ( new new byte [ 1024 ]); var receivedResult = the await socket.ReceiveAsync (Buffer, CancellationToken.None); // web socket for receiving asynchronous data 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 new ArraySegment < byte > (buffer.Array); the foreach ( var innerSocket in _sockets) // when a text message is received, all web socket connected to the server the current broadcast { IF (! = innerSocket Socket) { the await innerSocket .SendAsync (sendBuffer, WebSocketMessageType.Text, to true , CancellationToken.None); } } } } } }
front end:
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>