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连接:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. namespace WebSocketSample.Controllers  
  2. {  
  3.     public class WSChatController : ApiController  
  4.     {  
  5.         public HttpResponseMessage Get()  
  6.         {  
  7.             if (HttpContext.Current.IsWebSocketRequest)  
  8.             {  
  9.                 HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);  
  10.             }  
  11.             return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);  
  12.         }  
  13.    
  14.         private async Task ProcessWSChat(AspNetWebSocketContext arg)  
  15.         {  
  16.             WebSocket socket = arg.WebSocket;  
  17.             while (true)  
  18.             {  
  19.                 ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);  
  20.                 WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);  
  21.                 if (socket.State == WebSocketState.Open)  
  22.                 {  
  23.                     string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);  
  24.                     string returnMessage = "You send :" + message + ". at" + DateTime.Now.ToLongTimeString();  
  25.                     buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage));  
  26.                     await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);  
  27.                 }  
  28.                 else  
  29.                 {  
  30.                     break;  
  31.                 }  
  32.             }  
  33.         }  
  34.     }  
  35. }  
在这段代码中,只是简单的检查当前连接的状态,如果是打开的,那么拼接了接收到的信息和时间返回给浏览器端。
 
2.浏览器端
 
在另外一个视图中,我们使用了原生的WebSocket创建连接,并进行发送数据和关闭连接的操作

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. @Scripts.Render("~/Scripts/jquery-1.8.2.js")  
  5.    
  6. <script type="text/javascript">  
  7.     var ws;  
  8.     $(  
  9.         function () {  
  10.             $("#btnConnect").click(function () {  
  11.                 $("#messageSpan").text("Connection...");  
  12.                 ws = new WebSocket("ws://" + window.location.hostname +":"+window.location.port+ "/api/WSChat");  
  13.                 ws.onopen = function () {  
  14.                     $("#messageSpan").text("Connected!");  
  15.                 };  
  16.                 ws.onmessage = function (result) {  
  17.                     $("#messageSpan").text(result.data);  
  18.                 };  
  19.                 ws.onerror = function (error) {  
  20.                     $("#messageSpan").text(error.data);  
  21.                 };  
  22.                 ws.onclose = function () {  
  23.                     $("#messageSpan").text("Disconnected!");  
  24.                 };  
  25.             });  
  26.             $("#btnSend").click(function () {  
  27.                 if (ws.readyState == WebSocket.OPEN) {  
  28.                     ws.send($("#txtInput").val());  
  29.                 }  
  30.                 else {  
  31.                     $("messageSpan").text("Connection is Closed!");  
  32.                 }  
  33.             });  
  34.             $("#btnDisconnect").click(function () {  
  35.                 ws.close();  
  36.             });  
  37.         }  
  38.     );  
  39. </script>  
  40.    
  41. <fieldset>  
  42.     <input type="button" value="Connect" id="btnConnect"/>  
  43.     <input type="button" value="DisConnect" id="btnDisConnect"/>  
  44.     <hr/>  
  45.     <input type="text" id="txtInput"/>  
  46.     <input type="button" value="Send" id="btnSend"/>  
  47.     <br/>  
  48.     <span id="messageSpan" style="color:red;"></span>  
  49. </fieldset>  
3.测试结果
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值