Latest version of socket io nodejs is not connecting to flutter applications - node.js

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.

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.
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.
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.

Related

how to connect to socket.io on nodejs server using flutter?

I am developing a backend using node js and express framework and I will use socket.io in order to make a realtime connection between the server and the client ( flutter app ).
I have created a socket.io configuration on the server-side code and this is the code snippet:
const server = app.listen(port);
const io = require('socket.io')(server);
io.on('connection' , client => {
console.log('one connected');
});
and on the client side:
SocketIO socketIO;
socketIO = SocketIOManager().createSocketIO(SERVER_URL, '/');
socketIO.init().then(
(result) async {
await socketIO.subscribe('connection', (){});
await socketIO.connect();
},
);
the problem that I can't see one connected logged in the console of the node app.
it doesn't throw any error on the client-side and I want to know if I am on the right way.
Thanks,
After searching I found that the solution was to create my server using http plugin.

Flutter socket io doesn't connect to node js socket io server

I'm trying to build a simple flutter chat application using a node.js matchmaking server. I've worked with this for a few hours already but I simple cannot get the app to connect with the server.
Here's the node js server:
var express=require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var allClients = {};
io.on('connection', function (socket) {
io.to(socket.id).emit('userCount', Object.keys(allClients).length);
console.log(socket.id,'joined');
//match making logic
});
var port = 8080;
console.log(port);
server.listen(port);
Flutter connecting code:
//Find a match for the user
void findMatch() async {
SocketIO socketIO = SocketIOManager().createSocketIO("http://192.168.0.32:8080", "/");
print('Created');
await socketIO.init(); //code execution pauses indefinitely at this line
print('Initialized');
await socketIO.connect();
print('Connected');
socketIO.sendMessage('new user', data);
socketIO.subscribe('match found', (data) async {
UserData peerData = await getUserData(data.peerId);
redirectToPage(context, Chat(peerId: data.peerId, peerData: peerData));
});
}
When the function is run, the code execution pauses at the line shown above, and the node js server doesn't react at all. However this shows up on the debug console.
D/FlutterSocketIoPlugin: FlutterSocketIoPlugin( 4490): onMethodCall: socketInit - domain: http://192.168.0.32:8080 - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: added SocketIO( 4490): http://192.168.0.32:8080/
D/FlutterSocketIoPlugin: SocketIO( 4490): connecting...null
Any help is appreciated. Thank you!
I wrote a simple node js client as suggested in the comments, and it connects to the server successfully.
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Edit:
Removing the 'await's before the socket functions in findMatch() gets me this.
D/FlutterSocketIoPlugin: SocketIO(21368): reconnect_error: [{"cause":{"cause":{"detailMessage":"CLEARTEXT communication to 192.168.0.32 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"Connection error","stackTrace":[],"suppressedExceptions":[]}]
I tried android:usesCleartextTraffic="true" in AndroidManifest.xml but it doesn't seem to work. Changing http to https gives SSL handshake aborted. Maybe deploying the socket server on a remote machine with an SSL certificate will work? Will continue digging.
Downgrading my server's socket.io version worked for me. Just as above, if you are using nodejs try uninstalling socket.io and installing an older version as follows:
npm uninstall socket.io
npm install socket.io#2.3.0
Most flutter socket io client packages are compatible with socket.io version 2.3.0. I would recommend you downgrade to this incase you are experiencing a similar problem.
I tried above code with this flutter plugin here as I think you are also using the same, but I also got the same problem. I tried to see any error log generated by Logcat and I found an entry connecting...null and it was stuck there but don't know how to fix or what is the problem. I tried it with another flutter plugin here and tested it in emulator, it worked fine for below sample code. If you can use a different flutter plugin then this might be useful.
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log(socket.id, 'joined');
socket.on('/test', function (msg) {
console.log(msg);
});
});
var port = 8080;
console.log(port);
server.listen(port);
Flutter client code -
IO.Socket socket = IO.io('http://10.0.2.2:8080', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket.connect();
socket.emit('/test', 'test');
Try downgrading your server's socket io version. Some socket io client packages(flutter) are not compatible with the latest server-side socket io (node.js). My server configuration was using version 3.0.4. For some reason, it was incompatible with adhara_socket_io: 0.4.2 and socket_io_client: 0.9.12. By downgrading my node.js socket io version worked for both client libraries
npm uninstall socket.io
npm install socket.io#2.3.0
work too
server(nodejs) => "socket.io": "^2.4.1"
client(flutter) => socket_io_client: ^1.0.1

Using Socket.io in React Native and Hapi Server

I'm trying to setup a simple socket io system for my React Native App (using Expo) to send messages back and forth from my Node Hapi server. Right now I have a print out on the Server to print when a connection is established however it is never printed. My Node server is hosted on a Amazon AMI instance using port 3030. Here are some code snippets. Any idea why the connection is not being made?
Server Socket IO Code:
const io = require('socket.io')(server.listener);
io.on('connection', (socket) => {
console.log('Socket connection established.');
socket.emit('connection', true);
});
Client Socket IO Code:
const io = require('socket.io-client');
componentDidMount() {
this.socket = io('http://{my_aws_instance_public_ip}:3030', {
transports: ['websocket']
});
this.socket.on('connect_error', (err) => {
console.log(err)
});
}

Socket.io "Session ID unknown" error on Heroku

I have a Node JS app using Socket.io deployed to heroku. I have followed the steps provided at https://devcenter.heroku.com/articles/node-websockets to setup the code properly but somehow it seems like I am unable to use Web sockets properly.
All my socket polling requests are failing with the following error.
{"code":1,"message":"Session ID unknown"}
The same code seems to be working fine when I run it locally.
Client
function createSocket() {
socket = io();
socket.on('connect', function () {
socket.emit('registerUser', { userEmail: $scope.userInfo.userEmail });
});
socket.on('list_of_files', function (data) {
$timeout(function () {
$scope.fileList = data;
});
});
}
Server
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
socket.on('registerUser', function (data) {
socketClients[data.userEmail] = socket;
});
});
I have also enabled heroku's session affinity but still no luck
i know its too late but for those who still looking for the answer try adding this option on the client socket.
{
path: '/socket.io',
transports: ['websocket'],
secure: true,
}
also just for your information i'm having this problem after deploying to staging server with nginx and proxy
Same question on iOS platform, "session id unknown ..."
before
[[SocketIOClient alloc] initWithSocketURL:url config:#{#"log": #NO, #"forcePolling":#YES, #"reconnectWait":#1}];
after
[[SocketIOClient alloc] initWithSocketURL:url config:#{#"log": #NO, #"forcePolling":#YES, #"forceWebsockets":#YES}];

Why is my connection of a NodeJS server (Sails) to another NodeJS Server (Express4) using Socket.IO failing?

I am trying to connect my Node.JS (written using Sails.JS) app to another Node.JS server (Express4 / Socket.io) using socket.io-client.
My Sails Service app/services/Watcher.js looks like
var client = require('../../node_modules/sails/node_modules/socket.io/node_modules/socket.io-client');
// callback of the form function(socket)
exports.connect = function(callback) {
sails.log.debug("will connect socket to", sails.config.watcher.uri, "with Socket.io-client version", client.version);
var socket = client.connect(sails.config.watcher.uri);
socket.on('connect', function(){
sails.log.debug("connected");
socket.on('disconnect', function(){
sails.log.debug("Disconnected");
});
socket.on('error', function(err){
sails.log.debug("Could not connect", err);
});
callback(socket);
});
};
This is invoked from config/bootstrap.js as follows:
Watcher.connect(function(socket){
sails.log.debug("Connected watcher to relay with socket", socket);
});
On the Express side my server relay.js is as simple as:
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io').listen(http),
port = process.env.RELAY_PORT || 8000;
app.get('/', function(req, res) {
var response = {message: "some response"}; // to be implemented.
res.json(response);
});
http.listen(port, function () {
console.log("Relay listening on port " + port);
});
io.sockets.on('connection', function (socket) {
console.log("Connection opened", socket);
socket.on('disconnect', function () {
console.log("Socket disconnected");
});
});
When I run node relay it dutifully reports
Relay listening on port 8000
When I sails lift my other server it dutifully reports
will connect socket to http://localhost:8000 with Socket.io-client version 0.9.16
But I never see an actual connection.
If I point a browser at localhost:8000 I get the {"message":"some response"} JSON response I expect.
Why isn't my relay server accepting a connection from my socker.io-client app?
The issue here is probably that you're trying to re-use the
socket.io-client from inside of Sails. In general, if you're require()-ing dependencies of Sails directly in your project, you're heading in the wrong direction. In this case, socket.io-client caches configurations and connections, so your require isn't getting a fresh copy.
Instead, do
npm install socket.io-client#~0.9.16 --save
in your project and require with
var client = require('socket.io-client');
that'll give you a fresh copy of the socket client to work with, and avoid any conflicts with the Sails core's version.

Resources