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>