WebSocket 規范的目標是在瀏覽器中實現和服務器端雙向通信。雙向通信可以拓展瀏覽器上的應用類型,例如實時的數據推送、游戲、聊天等。有了WebSocket,我們就可以通過持久的瀏覽器和服務器的連接實現實時的數據通信,再也不用傻傻地使用連綿不絕的請求和常輪詢的機制了,費時費力,當然WebSocket也不是完美的,當然,WebSocket還需要瀏覽器的支持,目前IE的版本必須在10以上才支持WebSocket,Chrome Safari的最新版本當然也都支持。本節簡單介紹一個在服務器端和瀏覽器端實現WebSocket通信的簡單示例。
1.服務器端
我們需要在MVC4的項目中添加一個WSChatController並繼承自ApiController,這也是ASP.NET MVC4種提供的WEB API新特性。
在Get方法中,我們使用HttpContext.AcceptWebSocketRequest方法來創建WebSocket連接:
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(AspNetWebSocketContext 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; } } } } }
在這段代碼中,只是簡單的檢查當前連接的狀態,如果是打開的,那么拼接了接收到的信息和時間返回給瀏覽器端。
2.瀏覽器端
在另外一個視圖中,我們使用了原生的WebSocket創建連接,並進行發送數據和關閉連接的操作
@{ 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"/> <hr/> <input type="text" id="txtInput"/> <input type="button" value="Send" id="btnSend"/> <br/> <span id="messageSpan" style="color:red;"></span> </fieldset>