H5WebSocket前后台代码

Posted 光阴易逝,岂容我待

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了H5WebSocket前后台代码相关的知识,希望对你有一定的参考价值。

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

感谢帮助过我的朋友们

 

以上是关于H5WebSocket前后台代码的主要内容,如果未能解决你的问题,请参考以下文章

pbootcms对接微信扫码登录代码核心片段和步骤(前后端)

h5 websocket 是如何工作的

在后台堆栈中多次防止相同的片段

当 FragmentActivity 在 Android 中进入后台时出现 NotSerializableException

如何知道何时调用了`navController.popBackStack()`?

Android从后台堆栈中删除事务