Issue
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.
Solution
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();
}
Answered By - J Curti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.