问题
I'm creating an Electron application that uses websocket to communicate to a client application, but I'm experiencing an issue: The client can connect to the server via websocket but when it comes to sending messages from the client to the server, it does not work. It seems that the server is just simply not receiving the messages.
Server-side:
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) => {
// this part is not working. Messages are not being received and therefor it wont sent back any response
ws.on("message", (message: string) => {
console.log("received: %s", message);
ws.send(`Hello, you sent -> ${message}`);
});
//i get this message when i connect it with the client
ws.send("Hi there, I am a WebSocket server");
});
//start our server
server.listen(port, () => {
console.log(`Data stream server started on port ${port}`);
});
So far these are my findings:
I have my websocket server implementation on a renderer process. It seems the problem behind this small detail, because if I put the same code on the main process, everything works just fine (but it cannot be a solution, i need it on the renderer process).
Interestingly I can always connect to my websocket, so it seems that the socket is available, it just the messages that somehow cannot be emmited or received on the server side
The messages problem could be solved by connecting to my server with another client and sending a message. Weirdly at the moment I connect with a new client, my messages that were sent before (with another client) are 'triggered' and the server receives it, and then replies too. But then it doesnt work again, so I need a new client to connect again and send one message to solve all the 'stuck' client messages. (hope i was clear here, it's a bit confusing)
Not that i'm not sharing the client code, but there is no point to show, since everything works fine when i'm putting my code to the main process, or if I just run this js file with node itself. The only problem is the integration between electron renderer processes and websocket communication.
Hoping to find the answer soon, this community has always prove to be very strong in solving issues like this! :)
来源:https://stackoverflow.com/questions/58973435/electron-renderer-process-websocket-issue-bounty-for-the-solution