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

感谢帮助过我的朋友们

 

posted on 2017-09-21 18:24  王洪洪  阅读(2589)  评论(2编辑  收藏  举报