socket_io_client for socket connect triggering multiple times

1,133

Where are you calling the socket.connect() is the important part here. If our socket is connecting several times, maybe your method is triggered on a widget that is being re-renderized by state changes.

Try to move it to a new function called at the end of initState:

@override
void initState() {
 super.initState();

 this.connectToSocket();
}

void connectToSocket() {
  ...
}

EDIT: You also need to remove your socket on dispose, and use a reference to your socket:

Socket socket;

@override
  void initState() {
    super.initState();
      connectToSocket();
    });

 connectToSocket() {
    if(socket){ return; }
    socket = io('http://xyxz', <String, dynamic>{
        'query': {"sdsxyz"} // optional
      });
    socket.connect();
     }

 @override 
 void dispose() {
if(socket) {
  socket.disconnect();
}
super.dispose();

}

Share:
1,133
Divyam Joshi
Author by

Divyam Joshi

Updated on December 25, 2022

Comments

  • Divyam Joshi
    Divyam Joshi over 1 year

    I am using the socket_io_client library for the socket connection in the flutter app. for example

    @override
      void initState() {
        super.initState();
          connectToSocket();
        });
    
     connectToSocket() {
        Socket socket = io('http://xyxz', <String, dynamic>{
            'query': {"sdsxyz"} // optional
          });
        socket.connect();
         }
    

    calling this method at initState. for socket connect. but socket connection trigger(socket connected socket disconnected)multiple times at the server end.

    server-side code.

    const app = require('express')()
    const http = require('http').createServer(app)
    app.get('/', (req, res) => {
        res.send("Node Server is running. Yay!!")
    })
    //Socket Logic
    const socketio = require('socket.io')(http)
    socketio.on("connection", (userSocket) => {
        console.log("Socket connected", userSocket.id)
        userSocket.on("send_message", (data) => {
            userSocket.broadcast.emit("receive_message", data)
        })
    })
    

    I want that socket connection should be called once for the normal flow of data.

  • J Curti
    J Curti over 3 years
    are you disconnecting your socket on dispose() as well?
  • Divyam Joshi
    Divyam Joshi over 3 years
    No , i am not disconnecting socket and not understanding why socket connection disconnecting and connecting multiple times at server end. function called at the end of initState only.
  • J Curti
    J Curti over 3 years
    you should disconnect your socket on dispose(). I will update my answer
  • Divyam Joshi
    Divyam Joshi over 3 years
    hey, the same problem is happening connected sometimes disconnected multiple times. thanks for the help with this problem.