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) { ArraySegment<byte> buffer = new ArraySegment<byte>(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<byte>(Encoding.UTF8.GetBytes(userMsg)); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { break; } } } }
3、前端代碼
@{ ViewBag.Title = "Home Page"; } <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>
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
感謝幫助過我的朋友們