Ayush Agrawal
Ayush Agrawal

Reputation: 379

Latest version of socket io nodejs is not connecting to flutter applications

Currently, I am trying to use sockets with flutter application which works fine when I use version ^2.3.0. But when I tried using the latest version of socket io in nodejs i.e. 4.1.2, it didn't while it's still working with a browser. I am unable to figure out what's happening.

I am sharing the code for the flutter socket io connection as well as the nodejs application.

import 'package:getparked/Utils/DomainUtils.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;

class SocketUtils {
  IO.Socket socketIO;

  IO.Socket init(onSocketConnected, onSocketDisconnected) {
    socketIO = IO.io(domainName, <String, dynamic>{
      'transports': ['websocket'],
      'upgrade': false
    });

    socketIO.connect();
    socketIO.on("connect", (data) {
      print("Connection Successfully Established...");
      onSocketConnected(socketIO);
    });

    socketIO.on("reconnect", (data) {
      print("Socket Connected Again.. Reconnection");
    });

    socketIO.on("disconnect", (data) {
      print("Socket Disconnected Unexpectedly..");
      onSocketDisconnected(socketIO);
    });

    return socketIO;
  }
}

Node js Code

const express = require('express');
const app = express();
const server=require('http').createServer(app);
io = require('socket.io')(server, {
  cors:{
      origin:"*"
  },
});
io.on('connection', (socket) => { 
  console.log(socket.id);
});
server.listen(+port, () => {
  console.log("Server is running...");
  console.log(name + " " + port);
  vehicleUtils.init();
  adminUtils.init();
});

I anyone knows any way to fix this either in flutter or nodejs without downgrading the version please let me know.

Upvotes: 3

Views: 7703

Answers (1)

Ayush Agrawal
Ayush Agrawal

Reputation: 379

First of all, found the exact solution a few days after I posted it here. The problem is not with the backend or nodejs though it looks like a problem of the backend it isn't. enter image description here

I was using this exact version of the socket io client which is not suitable for the later versions of socket io in nodejs for connections.

Then I came to know about this which I found in the documentation of the socket io client in the pub. dev.

enter image description here

Then I just changed the version rebuilt it and it worked. Try changing the version of the socket io client in your Flutter app to 2.0 which will definitely solve your problem.

Upvotes: 12

Related Questions