1、效果图
2、前端代码
@{ ViewBag.Title = "Home Page";} @*HTML5 WebSocketWebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。以下 API 用于创建 WebSocket 对象。var Socket = new WebSocket(url, [protocol] );*@
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(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 buffer = new ArraySegment (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 (Encoding.UTF8.GetBytes(userMsg)); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } else { break; } } } }}