Reputation: 35
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.
Upvotes: 2
Views: 4231
Reputation: 954
solved by adding enableForceNewConnection()
socket = io(
'your socket url,
OptionBuilder()
.setTransports(['websocket'])
//add this line
.enableForceNewConnection() // necessary because otherwise it would reuse old connection
.disableAutoConnect()
.build());
Upvotes: 3
Reputation: 35
for Flutter: use socket_io_client
use property 'transports': ['webscoket']
link:https://pub.dev/packages/socket_io_client.
Why polling is not supported
'transports': ['polling'] does not support in Flutter, by default this library was designed for dart web, but dart web is not popular than Flutter; the polling mechanism is ported from Socket.io JS, which is using Ajax way to implement, but it's not allowed in dart:io library.
Upvotes: 0
Reputation: 3070
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();
}
Upvotes: 3