繼SignalR 持久連結 Web客戶端
阿新 • • 發佈:2020-09-16
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"); var connection = $.connection("http://106.12.125.134: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>