WebSocket simple attempt, websocket Attempt
System. Net. WebSockets. WebSocket
It must be. NET 4.5, IIS8 or above. IIS that comes with Windows Server2008R2 is not supported. IIS that comes with Windows 8 and Server2012 can
1. Implement IHttpHandler to process webSocket requests
Using System; using System. net. webSockets; using System. threading. tasks; using System. web; using System. web. webSockets; namespace WebSocketTest {public class MyWebSocketHandler: IHttpHandler {// <summary> // you cannot set the instance to be reused. // </summary> public bool IsReusable {get {return false ;}} /// <summary> /// determine whether a WebSocket request is handled by the handlerWebSocketAsync method /// </summary> /// <param name = "context"> </param> public void ProcessRequest (HttpContext context) {if (context. isWebSocketRequest) {context. acceptWebSocketRequest (handlerWebSocketAsync);} private async Task handlerWebSocketAsync (AspNetWebSocketContext context) {WebSocket webSocket = context. webSocket; await webSocket. sendMsgAsync ("connection successful"); while (true) {if (webSocket. state = WebSocketState. open) {string msg = await webSocket. receiveMsgAsync (); webSocket. sendMsgAsync (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + @ ", Receive:" + msg );}}}}}
WebSocket. ReceiveMsgAsync and webSocket. SendMsgAsync are two extension methods encapsulated by myself for string and byte [] conversion.
Using System; using System. net. webSockets; using System. text; using System. threading; using System. threading. tasks; namespace WebSocketTest {public static class WebSocketHelper {// <summary> // send a message // </summary> /// <param name = "webSocket"> </param> /// <param name = "msg"> </param> /// <returns> </returns> public static async Task SendMsgAsync (this WebSocket webSocket, string msg) {byte [] bytesMsg = Encoding. UTF8.GetBytes (msg); ArraySegment <byte> segment = new ArraySegment <byte> (bytesMsg); await webSocket. sendAsync (segment, WebSocketMessageType. text, true, CancellationToken. none );} /// <summary> /// receives the message // </summary> /// <param name = "webSocket"> </param> /// <returns> </returns> public static async Task <string> ReceiveMsgAsync (this WebSocket webSocket) {ArraySegment <byte> receiveSegment = new ArraySegment <byte> (new byte [1024]); WebSocketReceiveResult receiveResult = await webSocket. receiveAsync (receiveSegment, CancellationToken. none); string clientMsg = Encoding. UTF8.GetString (receiveSegment. array, 0, receiveResult. count); return clientMsg ;}}}
2. Add a Custom handler to web. Config. The integration mode needs to be configured on the <system. webServer> node. The classic mode is configured on the <system. web> node.
<system.web> <compilation debug="true" targetFramework="4.6.1"/>
3. Run VS for testing.
Running result