I am trying to create a websocket server that listen to an external websocket clinet. the point is I am laoding a web base application inside my browser window in electron. for example : win.loadURL(www.something); so the websocket call ing from this url meaning if I getinto this url in browser in my network tab I see websocket call is keep calling but there is no server. so I want to implement the server inside my electron app main.js. and here is my code:
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");
});
so far I did not get any success. any help would appriciate.
I am trying to create a websocket server that listen to an external websocket clinet. the point is I am laoding a web base application inside my browser window in electron. for example : win.loadURL(www.something.); so the websocket call ing from this url meaning if I getinto this url in browser in my network tab I see websocket call is keep calling but there is no server. so I want to implement the server inside my electron app main.js. and here is my code:
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");
});
so far I did not get any success. any help would appriciate.
Share Improve this question asked Nov 13, 2019 at 18:13 Samira ArabgolSamira Arabgol 3892 gold badges9 silver badges31 bronze badges1 Answer
Reset to default 5you need to start your http server mine looks like this:
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 ining 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}`);
});