• 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

    感谢帮助过我的朋友们

  • 相关阅读:
    [转载] python 计算字符串长度
    收藏好文章
    centos7安装部署kafka_2.13-2.4.1集群
    (转)zookeeper-3.5.5安装报错:找不到或无法加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain
    (转)Marathon私有镜像仓库用户名和密码方式
    centos7安装最新版git
    最新版Harbor搭建(harbor-offline-installer-v1.10.1.tgz)(转)
    安装不可描述服务端socket.error: [Errno 99] Cannot assign requested address错误:
    Integer值判断是否相等问题
    LVS实现Kubernetes集群高可用
  • 原文地址:https://www.cnblogs.com/honghong75042/p/7570059.html
Copyright © 2020-2023  润新知