简体   繁体   中英

How to setup a websocket with Javascript connected to Node-red

SO i have set myself with a project to turn on a light on RPi with node-red and a html document. So i have got all the node-red set up and it works along with the LED on my RPi. I installed apache2 and have been trying to start a websocket thing, but i have had no success.

<!DOCTYPE HTML>

<html>
   <head>
      
      <script type = "text/javascript">
         function WebSocketTest() {
            
            if ("WebSocket" in window) {
               alert("WebSocket is supported by your Browser!");
               
               // Let us open a web socket
               var ws = new WebSocket("ws://var/www/html/index.html");
                
               ws.onopen = function() {
                  
                  // Web Socket is connected, send data using send()
                  ws.send("Message to send");
                  alert("Message is sent...");
               };
                
               ws.onmessage = function (evt) { 
                  var received_msg = evt.data;
                  alert("Message is received...");
               };
                
               ws.onclose = function() { 
                  
                  // websocket is closed.
                  alert("Connection is closed..."); 
               };
            } else {
              
               // The browser doesn't support WebSocket
               alert("WebSocket NOT supported by your Browser!");
            }
         }
      </script>
        
   </head>
   
   <body>
      <div id = "sse">
         <a href = "javascript:WebSocketTest()" onclick="WebSocketTest()">Run WebSocket</a>
      </div>
      
   </body>
</html>

this is my code, and i have been trying to get it to work for ages, so i have come to the conclusion that this is not going to work

You can't use a file path for the websocket address.

It needs to be something like:

// Let us open a web socket
var ws = new WebSocket("ws://node-red.local:1880/foo");

Where Node-RED is running on node-red.local (you can probably swap this for the IP address) and you have configured a websocket-in node to bind to /foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM