如何使用连接到 Node-red 的 Javascript 设置 websocket

问题描述

所以我给自己设置了一个项目,用 node-red 和一个 html 文档打开 RPi 上的灯。所以我已经设置了所有节点红色,它与我的 RPi 上的 LED 一起工作。我安装了 apache2 并且一直在尝试启动 websocket 的事情,但是我没有成功。

<!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>

这是我的代码,我多年来一直试图让它工作,所以我得出的结论是这行不通

解决方法

不能为 websocket 地址使用文件路径。

它需要是这样的:

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

Node-RED 在 node-red.local 上运行的位置(您可以将其替换为 IP 地址)并且您已配置 websocket-in 节点以绑定到 /foo