Socket IO flutter not connecting
As per the socket_io client readme
In Flutter env. not (Flutter Web env.) it only works with dart:io websocket, not with dart:html websocket or Ajax (XHR), so in this case you have to add setTransports(['websocket']) when creates the socket instance.
Try adding an options Map
when you initialize your socket
.
This is just a different way of doing the same thing from the example in pub.dev
.
io.Socket socket = io.io("http://192.168.1.14:5000", <String, dynamic>{
"transports": ["websocket"],
});
On one of my projects I can confirm that it doesn't work without this being passed in.
Nachiket Kamod
Updated on January 04, 2023Comments
-
Nachiket Kamod about 1 year
I am facing an issue connecting my socket io flutter client to my nodejs socket io server. I am aware of the compatibility issue between the node socket io package and the flutter socket io client package. Hence, I installed only compatible versions of dependencies on both ends.
i.e., for flutter
socket_io_client: ^1.0.2
and for server side.
{ "socket.io": "^2.4.1", }
I have also tried the latest dependencies but I am getting the same timeout message in my logs, Initially, I thought it was my server's issue, but I checked the connection using postman and it works.
Below I am adding my implementations for both server and client side,
const { socketGuard } = require('./middlewares/socketio.middleware'); let io; module.exports = { init: (server) => { io = require("socket.io")(server, { cors: { origin: '*' } }); io.use(async (socket, next) => { let result = await socketGuard(socket); if (result.isValid) { next(); } else { next(new Error("Not authorized")); } }); io.on("connection", (socket) => { console.log(`${socket.id} : connected`); }); return io; }, get: () => { if (!io) { throw new Error("Socket io not initialized"); } return io; } };
and for flutter, I have added the following lines in the init function,
io.Socket socket = io.io("http://192.168.1.14:5000"); socket.onConnect((data) {log("Hello world");}); socket.onConnectError((data) {log(data);}); socket.onError((data) {log(data);}); socket.on("message", (data) {log(data);});
-
wildCat almost 2 yearsDid you mange to make it work? NodeJS side working fine. But flutter is not connecting nodejs socket.io!
-
Nachiket Kamod almost 2 yearsYes it's working now
-
-
Nachiket Kamod almost 2 yearsIf you don;t mind can elaborate why this happened
-
Nachiket Kamod almost 2 yearsActually my only mistake was that I tested with two implementation and in second implementation I must have done typo (websocket -> websockets), cause I believe I passed that argument before also, I am editing my implementation.