WebSocket | 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;
    //判断浏览器是否支持websocket
    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);
        }
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //将消息显示在网页上
    function send(e) {
        document.getElementById('message').innerHTML =e;
    }
    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容