1、效果图
2、后台代码:
public void Demo() { //return "Hello World"; HttpContextBase content = this.HttpContext; content.AcceptWebSocketRequest(ProcessChat); //return "I am a beautiful girl"; } private async Task ProcessChat(AspNetWebSocketContext context) { //HttpContextBase content = this.HttpContext; WebSocket socket = context.WebSocket; while (true) { if (socket.State == WebSocketState.Open) { ArraySegmentbuffer = new ArraySegment (new byte[2048]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); userMsg = "你发送了:" + userMsg + "于" + DateTime.Now.ToLongTimeString(); buffer = new ArraySegment (Encoding.UTF8.GetBytes(userMsg)); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { break; } } } }
3、前端代码
@{ ViewBag.Title = "Home Page";}
4、总结:看网上Websocket的实例后台一般都是ashx的样例,研究了好久才知道mvc的action也可以写成websocket。非常感谢eleven老师的指导。让我今天对websocket有了一定的了解,并且有信心坚持下去。也谢谢这位大牛的文章,让我解决了问题
https://stackoverflow.com/questions/40074190/websocket-connection-to-ws-localhost2017-failed-invalid-frame-header
还有这个文章
http://www.cnblogs.com/langu/archive/2013/12/22/3485676.html
感谢帮助过我的朋友们