WebSocket在ASP.NET MVC4中的简单实现
2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址:https://cloud.tencent.com/act/cps/redirect?redirect=1062
2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址:https://www.aliyun.com/minisite/goods
推荐:ASp.Net Websocket 环境支持和前端代码实现(二)
写文不容易,请尊重原创:转载注明 http://blog.csdn.net/meng6098 Websocket的环境支持: 1.支持html5的浏览器 经测试ie10和google可以用 2.Net服务器环境,.N
WebSocket 规范的目标是在浏览器中实现和服务器端双向通信。双向通信可以拓展浏览器上的应用类型,例如实时的数据推送、游戏、聊天等。有了WebSocket,我们就可以通过持久的浏览器和服务器的连接实现实时的数据通信,再也不用傻傻地使用连绵不绝的请求和常轮询的机制了,费时费力,当然WebSocket也不是完美的,当然,WebSocket还需要浏览器的支持,目前IE的版本必须在10以上才支持WebSocket,Chrome Safari的最新版本当然也都支持。本节简单介绍一个在服务器端和浏览器端实现WebSocket通信的简单示例。
1.服务器端
我们需要在MVC4的项目中添加一个WSChatController并继承自ApiController,这也是ASP.NET MVC4种提供的WEB API新特性。
在Get方法中,我们使用HttpContext.AcceptWebSocketRequest方法来创建WebSocket连接:
最近我们要做一个仿sina的微博,碰巧的是我最近在学习mvc,就想用mvc技术实现这个项目。 既然是微博,那不用想也应该知道肯定要有用户登陆,但是和常规的asp.net
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.测试结果

写文不容易,请尊重原创:转载注明 http://blog.csdn.net/meng6098 项目应用:与公司电话系统链接,实现客户来电时客服电脑弹窗提醒并显示该客户备忘信息功能。
相关阅读排行
- 1asp.net发布到IIS中出现错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
- 2[Asp.Net MVC4]验证用户登录实现
- 3检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法(非简单设置为【经典】模式)。 - CatcherX
- 4asp.net CheckBoxList 取值与勾选,复选框后台控制前台checkbox选中
- 5ASP.NET 3.5 企业级开发