无法使用JavaScript建立WebSocket连接

时间:2018-12-26 10:57:17

标签: javascript jquery websocket

这用于热敏打印,当我运行应用程序时,它在控制台中显示以下错误:

  

jquery.websocket.js:45未捕获的DOMException:无法执行“发送”   在“ WebSocket”上:仍处于CONNECTING状态。

代码:

 <script type="text/javascript">
     function connect() {
         debugger;
         var ws = new WebSocket("wss://192.168.1.23:9100");
         ws.onopen = function () {
             alert("About to send data");
             ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
             alert("Message sent!");
         };

         ws.onmessage = function (evt) {
             alert("About to receive data");
             var received_msg = evt.data;
             alert("Message received = " + received_msg);
         };
         ws.onclose = function () {
             // websocket is closed.
             alert("Connection is closed...");
         };
     };


</script>

1 个答案:

答案 0 :(得分:0)

已经对您的代码进行了测试,似乎可以正常工作。能否从您的侧面使用'wss://echo.websocket.org'网址进行检查? 我已经引用了https://www.websocket.org/echo.html url。下面是相同的代码

<!DOCTYPE html>
<html>
    <head>
        <title>To test web socket</title>
        <script type="text/javascript">
            function connect() {
                debugger;
                var ws = new WebSocket("wss://echo.websocket.org");
                ws.onopen = function () {
                    alert("About to send data");
                    ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
                    alert("Message sent!");
                };

                ws.onmessage = function (evt) {
                   alert("About to receive data");
                   var received_msg = evt.data;
                   alert("Message received = " + received_msg);
                };
                ws.onclose = function () {
                    // websocket is closed.
                   alert("Connection is closed...");
                };
            };
        </script>
    </head>
    <body>
       <button onclick="connect()">Connect</button>
    </body>
</html>