作者:wcx7758258 | 更新時間:2017-11-30 | 瀏覽量:1357
直接上源碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebSocket</title>
<!--
WebSocket實現溫濕度的模擬上傳
version:1.0
author:wcx0407@gamil.com
-->
</head>
<body>
<div id="getMsg">
<p id="printMsg">心跳次數:0</p>
<p id="printMsg1">非心跳返回值:0</p>
返回內容:<p id="printMsg2">null</p>
</div>
<form>
<input type="text" id="text1">
<input type="button" id="send1" value="發送溫度" onclick="sendTem()"><br><br>
<input type="text" id="text2">
<input type="button" id="send1" value="發送濕度" onclick="sendHum()"><br><br>
<input type="button" id="send2" value="查看是否在線" onclick="isOL()">
<input type="button" id="log" value="登陸溫濕度傳感器" onclick="logo()">
<input type="button" id="close" value="關閉連接" onclick="socket.close()">
</form>
<script>
var socket=new WebSocket("ws://www.eqytg.org:8383");
var temAndHumLogo="{\"M\":\"checkin\",\"ID\":\"xx1\",\"K\":\"xx2\"}\n"; //xx1為:設備ID ,xx2為:該設備的apikey
var tem1="{\"M\":\"update\",\"ID\":\"xx1\",\"V\":{\"xx3\":\""; //xx3為:該設備的溫度數據接口id
var hum1="{\"M\":\"update\",\"ID\":\"xx1\",\"V\":{\"xx4\":\""; //xx4為:該設備的濕度接口id
var temAndHum="\"}}\n";
var isol="{\"M\":\"isOL\",\"ID\":[\"xx5\"]}\n"; //xx5為:要查詢的設備id
var tem=0;
var hum=0;
//監聽WebSocket打開時的操作
socket.onopen=function(){
alert("WebSocket已打開!");
}
//監聽WebSocket關閉時的操作
socket.onclose=function(){
alert("WebSocket已關閉!");
}
//登陸溫濕度傳感器設備
function logo(){
socket.send(temAndHumLogo);
}
//查詢當前設備是否在線
function isOL(){
socket.send(isol);
}
//發送溫度數據
function sendTem(){
tem=document.getElementById("text1").value;
socket.send(tem1+tem+temAndHum);
}
//發送濕度數據
function sendHum(){
hum=document.getElementById("text2").value;
socket.send(hum1+hum+temAndHum);
}
//監聽服務器傳回信息時的操作,心跳保持在線,輸出返回信息
socket.onmessage=function(msg){
document.getElementById("printMsg2").innerHTML=msg.data;
if(msg.data=="{\"M\":\"ping\"}"){
document.getElementById("printMsg").innerHTML="心跳次數:"+(i++);
socket.send("ping");
}else{
document.getElementById("printMsg1").innerHTML="非心跳返回值:"+(j++);
socket.send("ping");
}
}
</script>
</body>
</html>