Implementing Web Sockets on the ASP. NET Web API

Source: Internet
Author: User
Tags socket error

1. What is a web Socket

The WEB socket is the communication mechanism introduced in HTML5, which provides a full-duplex TCP-based communication channel between the browser and the background server. A real-time solution that replaces the comet style of the previous longpooling. Based on the comparison between them and the advantages of the web socket refer to https://www.websocket.org/quantum.html.

2. How the WEB socket works

Connect

A WEB socket requires a handshake with a background server before it can be established. Specifically, the HTTP request is as follows:

HTTP/1.1Hostserver.example.comUpgradewebsocketConnectionUpgrade  Sec-websocket-keyx3jjhmbdl1ezlkh9gbhxdw==sec-websocket-protocolchat, Superchat  Sec-websocket-versionOriginhttp://example.com        

If the backend server supports switching to WebSocket, the following response will be returned:

HTTP/switching protocolsUpgradewebsocketConnection Upgrade sec-websocket-accept hsmrc0smlyukagmm5oppg2hagwk=sec-websocket-protocolchat        

The browser receives the response switch to the WebSocket channel based on the current TCP connection.

Data Transfer

After the connection is established, the browser side can communicate with the server to send the text type of message for full duplex, similar to TCP-based socket communication.

Disconnect

When the browser or the background server wants to terminate the communication, send a message of type close to the other party and wait for the other party to receive the message and confirm that the connection is broken.

3. Browser, server support situation

Refer to Wikipedia, the current browser support is as follows:

Ie Chrome Firefox Safari Opera
+ 16+ 11+ 6+ 12.10+

IIS supports Web sockets starting from 8.0

Well, after a long pave the formal entry coding:

1. In order to accept the browser-side handshake request, we need to define a Web API interface to accept the handshake request

[Routeprefix ("Api/chat")]    public class Chatcontroller:apicontroller    {        private static list<websocket> _sockets = new list< Websocket> ();        [Route]        [HttpGet]        Public Httpresponsemessage Connect (string nickname)        {            HttpContext.Current.AcceptWebSocketRequest ( ProcessRequest); Accept the web socket request on the server side, the incoming function as the Web socket handler function, the function will be called after the web socket is established, in which the web socket can be sent to the message            return Request.createresponse (Httpstatuscode.switchingprotocols); Constructs a response that agrees to switch to the web socket.        }    }

2. In order to send and receive a Web socket, you need to define the message transceiver function for the web socket (the previous. NET version is to accept an object that implements a particular interface, the new version is changed to accept a function, it is always weird), the code is as follows:

Public async Task ProcessRequest (Aspnetwebsocketcontext context) {var socket = context. The websocket;//incoming context has the current Web socket object _sockets. Add (socket);//Add a Web socket object to a static list here
       Enter an infinite loop when the web socket Close is loop over while (true) {var buffer = new ArraySegment <byte> (new byte[1024]); var receivedresult = await socket. Receiveasync (buffer, cancellationtoken.none);//asynchronously receives data for the web socket if (receivedresult.messagetype = = Websoc Ketmessagetype.close) {await socket. Closeasync (Websocketclosestatus.empty, String. Empty, Cancellationtoken.none);//If the client initiates a close request, the client is ACK _sockets. Remove (socket); Break } if (socket. state = = System.Net.WebSockets.WebSocketState.Open) {String recvmsg = Encoding.UTF8.Get String (buffer. Array, 0, Receivedresult.count); var recvbytes = Encoding.UTF8.GetBytes (recvmsg); var sendbuffer = new arraysegment<byte> (recvbytes); foreach (Var innersocket in _sockets)//When a text message is received, theAll Web socket connections on the current server are broadcast {if (Innersocket! = socket) { Await Innersocket.sendasync (Sendbuffer, Websocketmessagetype.text, True, Cancellationtoken.none) ; } } } }

Server-side code is ready, browser-side how to call it, continue to look at the code:

var webSocket = new WebSocket ("ws://localhost/api/chat?nickname=" + nickname.value);    Websocket.onopen = function () {        Console.log ("opened");    }    Websocket.onerror = function () {        console.log ("Web socket Error");    }    Websocket.onmessage = function (event) {
Console.log ("Web socket Error");


Self.webSocket.onclose = function () {Console.log ("closed");}

This creates a Web socket connection and receives the message, and of course there is an interface to send the message:

Websocket.send ("Hello Web Socket");

Here, the full-duplex communication mechanism based on the web socket has been established. The demo in this article is a simple chat room program. Code Link: https://github.com/lbwxly/WebSocketSample

Add:

HttpContext's Acceptwebsocketrequest method can only accept a function is a bit inconvenient, it is also not conducive to encapsulation and reuse. Therefore, an overloaded extension method for accepting objects is added, and then a class websockethandler is defined to handle the sending and receiving of messages and the closing of the connections. See the code link above.

Implementing Web Sockets on the ASP. NET Web API

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.