作者:wcx7758258 | 更新时间:2017-11-30 | 浏览量:1660
直接上源码
<!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.bigiot.net: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>