Sam*_*gol 3 javascript websocket node.js electron
我正在尝试创建一个监听外部 websocket 客户端的 websocket 服务器。重点是我正在电子浏览器窗口中加载一个基于网络的应用程序。例如:win.loadURL(www.something.com); 因此,来自此 url 的 websocket 调用意味着如果我在网络选项卡中的浏览器中进入此 url,我会看到 websocket 调用正在继续调用,但没有服务器。所以我想在我的电子应用程序 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");
});
Run Code Online (Sandbox Code Playgroud)
到目前为止我还没有取得任何成功。任何帮助将不胜感激。
你需要启动你的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}`);
});
Run Code Online (Sandbox Code Playgroud)