继SignalR 持久链接 Web客户端

SignalR 持久链接

简单模拟连接等操作

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>简单聊天程序</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.3.min.js"></script>
    <div>
        <h1>Echo service</h1>
        <div>
            <p>请输入发送的内容:</p>
            <textarea id="text"></textarea>
            <button id="send">Send</button>
        </div>
        <script>
            var userid = "98484844|1";
            //本地
            var connection = $.connection("http://127.0.0.1:9999/signalr");
            connection.logging = true;
            //客户端接收消息
            connection.received(function (data) {
            var json = JSON.parse(data);
                //模拟茉莉模拟发送
                if(json["type"]=="ng"&&json["text"]=="getall"){
                    connection.send({     "type": "ng",     "text": "getall",     "result": {         "mode": "on",         "handop": "on",         "disable": "on",         "gps": "on",         "wifi": "off",         "bluetooth": "off",         "nfc": "on",         "camera": "off",         "mike": "on"     } });
                } else  if(json["type"]=="ng"){
                    json.result=1;
                    connection.send(json);
                }
                $(document.body).append(data+"<br/>");
            });
            //连接错误处理
            connection.error(function (err) {
                alert('与服务器连接报错:'+err.message);
            });
            //连接成功
            connection.qs={userid:userid};
            connection.start().done(function () {
                $(document.body).append("连接成功<br/>")
                //connection.send({ type: "Online", text: userid });
                $('#send').click(function () {
                    var val = $('#text').val();
                    //向服务器端发送消息
                    connection.send(val);
                });
            });
            //重新连接执行上线
            connection.reconnected(function() {
                //connection.send({ type: "Online", text: userid });
            });

            //状态变更跟踪
            connection.stateChanged(function (change) {
                if (change.newState === $.signalR.connectionState.reconnecting) {
                    console.log('Re-connecting');
                }
                else if (change.newState === $.signalR.connectionState.connected) {
                    console.log('The server is online');
                } 
            });
            
        </script>
    </div>
</body>
</html>
原文地址:https://www.cnblogs.com/zengtianli/p/13679189.html