简体   繁体   中英

Websockets connecting multiple times in React JS + Electron NodeJS application

I have an application built in Electron JS, that uses React and websockets.

I'm calling the server in a renderer thread with this code:

const host = 'http://localhost:3000';

const socket = io(host);
const apiClient = new APIClient(socket);
apiClient.someMethod(...);

This code IS NOT inside a React JS component. It's on index.tsx, which is called only once. If I put a console.log in that code it only gets printed once.

In the server I have a code similar to this one:

    io.on("connection", socket => {
      // getting sesionUserId

      console.log("Client connected. User id: ", sessionUserId);

The code doesn't seem to work and in the server I get this log:

Client connected. User id:  5
Client connected. User id:  5
Client connected. User id:  5
Client connected. User id:  5
Client connected. User id:  5
... etc

Which seem to happen is that websockets are connecting all the time. Why could be this? I don't have much experience with Electron. It looks like the client can connect with the server, but for some reason it retries to connect. Also, when I try to speak to the server I don't get an answer (which I guess it's because it's reconnecting all the time).

Is there any restriction on Electron JS that it prevents websockets to work properly?

are you using different version of socketIO on client and server, try to make them of same major version. This happened to me when I had different version where I had version 2.XX at client and 3.XX at server. so I made both version of socketIO for both server and client to 2.XX and everything started working fine.
ie I used 'socket-io-client' module at client of version 2.XX at client side and I used 'socket-io' module at server of version 2.XX and no more multiple websocket connection was being formed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM