web | html websocket客户端

web | html websocket客户端

简单记录一下,忘了参考的链接是哪里的了。。。

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>websocket</title>
 </head>
 <body>
 <input id="text" value="">
 <input type="submit" value="send" onclick="start()">
 <input type="submit" value="close" onclick="close()">
<div id="msg"></div>
 <script>
 /**
 0:未连接

1:连接成功,可通讯

2:正在关闭

3:连接已关闭或无法打开
*/

    //创建一个webSocket 实例
    var _url = "ws://127.0.0.1:2333";
    var webSocket  = new  WebSocket(_url);


    webSocket.onerror = function (event){
        onError(event);
    };

    // 打开websocket
    webSocket.onopen = function (event){
        onOpen(event);
    };

    //监听消息
    webSocket.onmessage = function (event){
        onMessage(event);
    };


    webSocket.onclose = function (event){
        onClose(event);
    }

    //关闭监听websocket
    function onError(event){
        document.getElementById("msg").innerHTML = "<p>close</p>";
        console.log("error"+event.data);
    };

    function onOpen(event){
        console.log("open:"+sockState());
        document.getElementById("msg").innerHTML = "<p>Connect to Service</p>";
        document.getElementById("msg").innerHTML += '<p>连接到: '+_url+'</p>';
    };
    function onMessage(event){
        console.log("onMessage");
        document.getElementById("msg").innerHTML += "<p>response: "+event.data+"</p>"
    };

    function onClose(event){
        document.getElementById("msg").innerHTML = "<p>close</p>";
        console.log("close: "+sockState());
        webSocket.close();
    }

    function sockState(){
        var status = ['未连接','连接成功,可通讯','正在关闭','连接已关闭或无法打开'];
            return status[webSocket.readyState];
    }



 function start(event){
        console.log(webSocket);
        var msg = document.getElementById('text').value;
        document.getElementById('text').value = '';
        console.log("send:"+sockState());
        console.log("msg="+msg);
        webSocket.send("msg="+msg);
        document.getElementById("msg").innerHTML += "<p>request"+msg+"</p>"
    };

    function close(event){
        webSocket.close();
    }
 </script>
 </body>
</html>


posted @ 2022-07-20 12:46  Mz1  阅读(29)  评论(0编辑  收藏  举报