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

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

Related

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

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.

Laravel 5 - Homestead - Redis - NodeJs - Socket IO not playing nicely

I am attempting to get some real time notifications into my Laravel 5 app. Building locally on a vagrant box with Homestead.
I can not work out what the issue is with the following set up.
My server.js is as follows ...
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(3000);
io.on('connection', function (socket) {
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
Then my client code is to subscribe:
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('message', function (data) {
alert(data);
});
</script>
Firebug keeps returning:
GET http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=1430825965165-1
Aborted
Chrome tools shows me the following:
http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=1430826106108-3 net::ERR_CONNECTION_REFUSED
Pretty new to NodeJs and very confused. Spent a good 4 hours now trying to work it out.
Any pointers?
many thanks, Dean.
First make sure that you have installed all dependencies of your server.js file, if you are working with Homestead, execute the following command in your root project directory:
npm install express redis socket.io --save
Wait until installation finish and start the server with:
node server.js
Use your project's virtual host name for connect with socket.
It works for me.
Edit this in your client code.
var socket = io.connect('http://' + location.host + ':3000');

Testing node websockets with telnet

I am writing a socket-based server in Node js using the ws library, and I would like to test that my code works. I have seen telnet used elsewhere to test simple chat servers, but when I start my server and execute telnet 127.0.0.1 5000, although the output says "connected to localhost", my server doesn't log anything associated with a new connection. Am I testing my server wrong or is my server simply not working? My server code is below:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
var server = http.createServer(app);
server.listen(port);
var wss = new WebSocketServer({server: server});
console.log('websocket server created');
wss.on('connection', function(ws) {
var id = setInterval(function() {
ws.send(JSON.stringify(new Date()), function() { });
}, 1000);
console.log('websocket connection open');
ws.on('close', function() {
console.log('websocket connection close');
clearInterval(id);
});
});
You connected to HTTP server, but did not established WebSocket connection. That's why your script doesn't print anything.
I'm not sure you can test websocket manually, look at the handshake.
But there are a few telnet-like programs that work with websocket. Maybe wscat from ws module you're using will help with that.
I found https://www.websocket.org/echo.html To be useful. Just create a websocket.index file on your hard-drive if you are testing a localhost server. Code is on the bottom of the page.
UPD: as per #jouell's note, it looks like this tool is now out of date
This little tool did the job for me: https://github.com/lafikl/telsocket
brew tap pascaliske/telsocket
brew update
brew install telsocket
telsocket -url ws://127.0.0.1:50000
(for people who don't use npm)

Use of Socket.io and express 4.3 with express-generator

I'm trying to use socket.io with express 4 and express-generator, however I'm having an issue that the connection event from socket.io don't fires. I have the following settings for my project:
./bin/www
var load = require('express-load');
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io').listen(server, {});
load('sockets').into(io);
socket/chat.js
module.exports = function (io) {
var sockets = io.sockets;
sockets.on('connection', function (client) {
console.log('A user had connected: ', client);
});
console.log('Sockets Events: ', sockets._events.connection);
};
The function of the event is properly logged to the conseole, but when I try to connect I don't receive the log from the event.
I already tried the solutions on this thread: Using socket.io in Express 4 and express-generator's /bin/www
But none solved my issue, thanks in advance.

Resources