1、效果图
2、前端代码
@{ ViewBag.Title = "Home Page"; } @*HTML5 WebSocket WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。 浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。 当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。 以下 API 用于创建 WebSocket 对象。 var Socket = new WebSocket(url, [protocol] );*@ <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> var ws; $().ready(function () { $('#conn').click(function () { ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Home/Demo'); $('#tips').text('正在连接'); ws.onopen = function () { $('#tips').text('已经连接'); } ws.onmessage = function (evt) { $('#tips').text(evt.data); } ws.onerror = function (evt) { $('#tips').text(JSON.stringify(evt)); } ws.onclose = function () { $('#tips').text('已经关闭'); } }); $('#close').click(function () { ws.close(); }); $('#send').click(function () { if (ws.readyState == WebSocket.OPEN) { ws.send($('#content').val()); } else { $('#tips').text('连接已经关闭'); } }); }); </script> <br/> <div class="row"> <form id="form1" runat="server"> <div> <input id="conn" type="button" value="连接" /> <input id="close" type="button" value="关闭" /> <span id="tips"></span> <input id="content" type="text" /> <input id="send" type="button" value="发送" /> </div> </form> </div>
2、后端代码
using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.WebSockets; namespace H5WebSocket.Controllers { public class HomeController : Controller { WebSocket socket = null; public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public void Demo() { //return "Hello World"; HttpContextBase content = this.HttpContext; content.AcceptWebSocketRequest(ProcessChat); //return "I am a beautiful girl"; } public String onMessage(String message) { while (true) { var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } private async Task ProcessChat(AspNetWebSocketContext context) { //HttpContextBase content = this.HttpContext; socket = context.WebSocket; while (true) { if (socket.State == WebSocketState.Open) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); while (true) { Thread.Sleep(100); string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); userMsg = "你发送了:" + DateTime.Now.ToLongTimeString() + "于" + DateTime.Now.ToLongTimeString(); buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMsg)); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } else { break; } } } } }