Simple implementation of WebSocket in ASP. NET MVC4

Source: Internet
Author: User

WebSocket's simple implementation of ASP. NET MVC4 at 2013-12-21 by, 558 reading, 3 comments, favorites, and editing WebSocket specifications aims to achieve bidirectional communication with the server in the browser. Two-way communication can expand the application types on the browser, such as real-time data push, games, and chat. With WebSocket, we can achieve real-time data communication through persistent connections between browsers and servers. We no longer need to use the endless requests and polling mechanism, which is time-consuming and laborious, of course, WebSocket is not perfect. Of course, WebSocket also requires browser support. Currently, the IE version must be 10 or later to support WebSocket, and the latest version of Chrome Safari is also supported. This section describes a simple example of WebSocket communication between the server and the browser. 1. on the server side, we need to add a WSChatController in the MVC4 project and inherit from ApiController. This is also a new web api feature provided by ASP. NET MVC4. In the Get method, we use HttpContext. use the AcceptWebSocketRequest method to create a WebSocket connection: namespace WebSocketSample. controllers {public class WSChatController: ApiController {public HttpResponseMessage Get () {if (HttpContext. current. isWebSocketRequest) {HttpContext. current. acceptWebSocketRequest (ProcessWSChat);} return new HttpResponseMessage (HttpStatusCode. switchingProtocols);} private async Task ProcessWSChat (AspNe TWebSocketContext arg) {WebSocket socket = arg. webSocket; while (true) {ArraySegment <byte> buffer = new ArraySegment <byte> (new byte [1024]); WebSocketReceiveResult result = await socket. receiveAsync (buffer, CancellationToken. none); if (socket. state = WebSocketState. open) {string message = Encoding. UTF8.GetString (buffer. array, 0, result. count); string returnMessage = "You send:" + message + ". At "+ DateTime. now. toLongTimeString (); buffer = new ArraySegment <byte> (Encoding. UTF8.GetBytes (returnMessage); await socket. sendAsync (buffer, WebSocketMessageType. text, true, CancellationToken. none);} else {break ;}}} in this code, it simply checks the status of the current connection. If it is enabled, the received information and time are spliced and returned to the browser. 2. in another view, the browser uses the native WebSocket to create a connection, send data, and close the connection. @ {ViewBag. title = "Index" ;}@ Scripts. render ("~ /Scripts/jquery-1.8.2.js ") <script type =" text/javascript "> var ws; $ (function () {$ (" # btnConnect "). click (function () {$ ("# messageSpan "). text ("Connection... "); ws = new WebSocket (" ws: // "+ window. location. hostname + ":" + window. location. port + "/api/WSChat"); ws. onopen = function () {$ ("# messageSpan "). text ("Connected! ") ;}; Ws. onmessage = function (result) {$ ("# messageSpan "). text (result. data) ;}; ws. onerror = function (error) {$ ("# messageSpan "). text (error. data) ;}; ws. onclose = function () {$ ("# messageSpan "). text ("Disconnected! ") ;};}); $ (" # BtnSend "). click (function () {if (ws. readyState = WebSocket. OPEN) {ws. send ($ ("# txtInput "). val ();} else {$ ("messageSpan "). text ("Connection is Closed! ") ;}}); $ (" # BtnDisconnect "). click (function () {ws. close ();});}); </script> <fieldset> <input type = "button" value = "Connect" id = "btnConnect"/> <input type = "button" value = "DisConnect" id = "btnDisConnect"/>

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.