1. 程式人生 > >WebSocket在ASP.NET MVC4中的簡單實現

WebSocket在ASP.NET MVC4中的簡單實現

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>
3.測試結果