<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
var userId;
window.onload=function openSocket() {
userId=document.getElementById("userId")
userId.innerHTML=Math.ceil(Math.random()*200)
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
var socketUrl="http://192.168.110.224:9999/cmdi/monitorProjectStatus";
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() {
console.log("websocket已打开");
};
socket.onmessage = function(event) {
console.info(event.data)
console.info(isJson(event.data))
};
socket.onclose = function() {
console.log("websocket已关闭");
};
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function isJson($string)
{
try {
if(typeof JSON.parse($string) == 'object')
return true;
return false;
} catch (e) {
console.log(e);
return false;
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
console.info(fun().length!=0)
if(fun().length!=0){
console.info('{"privateUsers":"'+check_val + '"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
socket.send('{"privateUsers":"'+ check_val + '","userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
console.info(check_val)
}else{
console.log("您的浏览器支持WebSocket");
console.log('{"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
socket.send('{"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
}
}
}
function fun(){
obj = document.getElementsByName("onlineCheckBox");
check_val = [];
for(k in obj){
if(obj[k].checked)
check_val.push(obj[k].value);
}
return check_val
}
</script>
<body>
<div id="content" style="overflow:auto; height: 200px; width: 400px; border: 1px solid #999;" > </div>
<p>【UserId:】<span id="userId"></span></p>
<div>【内容:】<input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<button onclick="sendMessage()">发送</button>
<h4>在线用户列表</h4>
<div id="onlineUsers"><div>
</body>
</html>