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 classChatcontroller:apicontroller {Private StaticList<websocket> _sockets =NewList<websocket>();        [Route] [HttpGet] PublicHttpresponsemessage Connect (stringnickname)  {HttpContext.Current.AcceptWebSocketRequest (ProcessRequest);//accept the Web socket request on the server side, the incoming function as the Web socket handler function, the Web The function is called after the socket is established, where you can send and receive messages to the Web socket.returnRequest.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 AsyncTask ProcessRequest (Aspnetwebsocketcontext context) {varSocket =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 the end of the loop while(true) { varBuffer =Newarraysegment<byte> (New byte[1024x768]);varReceivedresult =awaitsocket. Receiveasync (buffer, cancellationtoken.none);//asynchronously receives data for a Web socketif(Receivedresult.messagetype = =websocketmessagetype.close) {awaitSocket. 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) {stringrecvmsg = Encoding.UTF8.GetString (buffer. Array,0, Receivedresult.count); varRecvbytes =Encoding.UTF8.GetBytes (recvmsg); varSendbuffer =Newarraysegment<byte>(recvbytes); foreach(varInnersocketinch_sockets)//When receiving a text message, broadcast all Web socket connections on the current server {if(Innersocket! =socket) { awaitInnersocket.sendasync (Sendbuffer, Websocketmessagetype.text,true, Cancellationtoken.none); } } } }

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

New WebSocket ("ws://localhost/api/chat?nickname=" + nickname.value);     function () {        Console.log ("opened");     }    function  () {        Console.log ("Web socket Error");    }     function (event) {
Console.log ("Web socket Error");


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

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.