WebSocket

作者: WWWWWWWWWWWWWWM | 来源:发表于2021-01-22 11:02 被阅读0次
    • 注意:
      webscoket.onopen这个事件在new WebSocket("ws://localhost:9998")的时候如果readyStatus 是 1 他会自动调用,因此如果你在new的时候,没有声明onopen,那么就不会调用了
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div>
            <button id="connection">连接</button>
            <button id="send" disabled>发送</button>
            <h1 id="label"></h1>
        </div>
    
        <script>
            let connection = document.querySelector("#connection");
            let send = document.querySelector("#send");
            let label = document.querySelector("#label");
            let webscoket = null;
            webscoket = new WebSocket("ws://localhost:9998");
            connection.onclick = function () {
               
                console.log(webscoket)
                webscoket.onopen = (a) => {
                    console.log("连接成功");
                    send.disabled = false;
                };
                webscoket.onclose = (a) => {
                    // console.log(a);onopen
                    console.log("连接失败");
                    send.disabled = true;
                };
                webscoket.onmessage = (msg) => {
                    label.innerHTML = msg.data
                }
            };
            send.onclick = function() {
        
                webscoket.send(1111)
            }
        </script>
    </body>
    </html>
    
    image.png

    相关文章

      网友评论

          本文标题:WebSocket

          本文链接:https://www.haomeiwen.com/subject/aodszktx.html