WebSocket的实用方法
//打开事件
socket.onopen = function(msg) {
console.log(msg);
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
//发送消息给后台
socket.send(JSON.stringify(obj));
实用例子:
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
var socketUrl="http://192.168.31.157:8888/websocketserver";
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function(msg) {
console.log(msg);
};
}
}
//发送消息给后台
function sendMessage1() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
console.log("您的浏览器支持WebSocket");
var data = {
"token": "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQ.........",
"prisonsId": "916287014690533376",
"isPolice":true
}
var obj={
"command": "connect",
"data": JSON.stringify(data),
}
socket.send(JSON.stringify(obj));
//发送消息过后,这里可以接收消息处理,前端逻辑
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
}
}
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value=""></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value=""></div>
<p>【消息】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<button οnclick="openSocket()">开启socket</button>
<p>【操作】:<button οnclick="sendMessage1()">验证</button>
<p>【操作】:<button οnclick="sendMessage2()">获取购物计划信息</button>
<p>【操作】:<button οnclick="sendMessage3()">通知下载</button>
</body>
</html>