Javascript 在electron节点中为外部客户端请求创建websocket服务器

Javascript 在electron节点中为外部客户端请求创建websocket服务器,javascript,node.js,websocket,electron,Javascript,Node.js,Websocket,Electron,我正在尝试创建一个websocket服务器,该服务器侦听外部websocket客户端。 重点是,我正在电子浏览器窗口中安装一个基于web的应用程序。 例如:win.loadURLwww.something.com;因此,来自此url的websocket调用 这意味着,如果我在浏览器的“网络”选项卡中进入此url,我会看到websocket调用为keep 正在呼叫,但没有服务器。所以我想在我的electron应用程序main.js中实现服务器。这是我的代码: const WebSocket = r

我正在尝试创建一个websocket服务器,该服务器侦听外部websocket客户端。 重点是,我正在电子浏览器窗口中安装一个基于web的应用程序。 例如:win.loadURLwww.something.com;因此,来自此url的websocket调用 这意味着,如果我在浏览器的“网络”选项卡中进入此url,我会看到websocket调用为keep 正在呼叫,但没有服务器。所以我想在我的electron应用程序main.js中实现服务器。这是我的代码:

const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 8102});

wss.on("connection", ws => {
    ws.on("message", message => {
        console.log("received: %s", message);
    });
    ws.send("something");
});

到目前为止,我没有取得任何成功。任何帮助都是值得的

您需要启动http服务器 我的看起来像这样:

import http from "http";
import * as WebSocket from "ws";

const port = 4444;
const server = http.createServer();
const wss = new WebSocket.Server({ server });

wss.on("connection", (ws: WebSocket) => {
  //connection is up, let's add a simple simple event
  ws.on("message", (message: string) => {
    //log the received message and send it back to the client
    console.log("received: %s", message);
    ws.send(`Hello, you sent -> ${message}`);
  });

  //send immediatly a feedback to the incoming connection
  ws.send("Hi there, I am a WebSocket server");
});

//start our server
server.listen(port, () => {
  console.log(`Data stream server started on port ${port}`);
});

您需要启动http服务器 我的看起来像这样:

import http from "http";
import * as WebSocket from "ws";

const port = 4444;
const server = http.createServer();
const wss = new WebSocket.Server({ server });

wss.on("connection", (ws: WebSocket) => {
  //connection is up, let's add a simple simple event
  ws.on("message", (message: string) => {
    //log the received message and send it back to the client
    console.log("received: %s", message);
    ws.send(`Hello, you sent -> ${message}`);
  });

  //send immediatly a feedback to the incoming connection
  ws.send("Hi there, I am a WebSocket server");
});

//start our server
server.listen(port, () => {
  console.log(`Data stream server started on port ${port}`);
});