html创建websocket链接
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="width:400px;margin:20px auto;border:1px solid lightgray;padding:20px;text-align:center;">
websocket 返回消息:¥<span style="color:#ff4719" id="message">没收到消息</span>
</div>
</body>
<script type="text/javascript">
var websocket=null;
if('WebSocket' in window){
websocket=new WebSocket("ws://127.0.0.1:8901/alarmRtime/html");
websocket.onopen=function(){
websocket.send("{\"type\":\"html\",\"authorization\":\"fd277a6e83b60b232256ebc43d4b5e5a\"}");
}
websocket.onerror=function(){
websocket.send("测试客户端连接失败");
send("测试客户端连接失败");
}
websocket.onclose=function(){
websocket.send("测试客户端连接关闭");
send("测试客户端连接关闭");
}
websocket.onmessage=function(e){
console.log("onmessage-----------------",e)
send(e.data);
}
window.onbeforeunload = function () {
closeWebSocket();
}
}
else {
alert('当前浏览器 Not support websocket')
}
function send(e) {
document.getElementById('message').innerHTML =e;
}
function closeWebSocket() {
websocket.close();
}
</script>
</html>
|