Home > Mobile >  socket io server connection fires multiple times
socket io server connection fires multiple times

Time:09-20

I am trying to create a basic game using next.js and node.js. When I run it I get multiple "connected" logs and when I check adapters -using io.sockets.adapter.rooms- I get even though there is just one client (One tab on chrome) connected:

io.sockets.adapter.rooms log:

 Map(4) {
  'tiTjbdGFj3EGgbwRAAAB' => Set(1) { 'tiTjbdGFj3EGgbwRAAAB' },
  'DsCKvImAuh8H6Vr3AAAD' => Set(1) { 'DsCKvImAuh8H6Vr3AAAD' },
  'FtJispkyF08rhHBDAAAF' => Set(1) { 'FtJispkyF08rhHBDAAAF' },
  'PFO72' => Set(1) { 'FtJispkyF08rhHBDAAAF' }
}

app.js(server backend)

const app = require('express')();
const server =  require('http').createServer(app);
const fs = require('fs');
const dirImage = './public/images';
const path = require( 'path' );

const io = require('socket.io')(server, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"],

    }
});
server.listen(8000);

frontend react context socket connection:

import {createContext} from 'react';
import io from "socket.io-client";



    export const socket = io("http://localhost:8000", {transports : ['websocket']});


    export const SocketContext = createContext(socket);

Also creating socket variable in every page using useContext hook:

    const socket = useContext(SocketContext);

When I run the server I still get 5 connections from one client

Connected! 
 Connected! 
 Connected! 
 Connected! 
 Connected!

What is the problem?

CodePudding user response:

from your frontend app, you are using context api to connect socket but not using useEffect Hooks, So your connection line is running multiple time as how many time your app is re-rendering. I suggest to use useEffect hook with empty dependency array to run the connection only in first render.

I am attaching a sample code for you:

  import io from "socket.io-client";

  useEffect(() => {
      socket = io.connect("http://localhost:8000");

      return () => {
        socket.disconnect();
      };
  
  }, []);

This will connect your socket connection first time and it will disconnect when the component ejects.

CodePudding user response:

Should it be like this?

context file:

const SocketContext = createContext();


const SocketContextProvider = ({children}) =>{
     const [socket,setSocket] = useState(null);
    useEffect(()=>{
          setSocket(io.connect("http://localhost:8000"));

    },[]);
     return (
         // the Provider gives access to the context to its children
         <SocketContext.Provider value={socket}>
              {children}
         </SocketContext.Provider>
     );

}
export {SocketContext,SocketContextProvider}
  • Related