Node.js Socket.io client on Flask socket.IO server - node.js

I'm trying to connect a Node.js Socket.IO client to a Python/Flask Socket.IO server.
On the server (Raspberry Pi) runs this project: Pi-GPIO-Server. This project already has a built-in website which is a socket.io client to access the pins of the Raspberry Pi.
The whole project works well.
Now I'd like to access the socket.io connection from a Node.JS client.
On the server side, I've updated the IP and port of the server to:
if __name__ == '__main__':
socketio.run(app, host="192.168.0.8", port=5000)
On the client side my implementation is (as stated in the documentation of the project)
var io = require('socket.io-client');
var socket = io.connect('http://192.168.0.8:5000', {path: '/', transports: ['websocket']});
socket.on( 'connect', (socket) => {
console.log('Connected: ');
console.log(socket);
});
socket.on( 'pins:list', (list) => {
console.log('List of Pins: ');
console.log(list);
});
Any ideas, why I cannot get a connection?
Is there a limitation of clients in the Flask server? Any special command to send?
Is there a possibility to debug the connection?

#Christoph Please use the below code you should be able to connect...I have Flash server running and Nodejs as a client, It is working fine for me!!!
In my case i am running both server and client in same machine so i used localhost in place of IP address
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from python flask srver");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect agan with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});

Related

Unable to connect to socket.io server over local network

I am trying to set up communication between my nodeJS server and a vueJS app via socket.io. I have been able to get the socket communication working on my main computer so far. When running my node server and my vue app in dev mode, I can open the vue app in the browser and I see the connection coming through my server.
However, when I open the vueJS app on my iPad (connected to the same wifi) the vue app loads and runs fine but my socket connection never goes through. I am also unable to connect to the socket server by opening the vueJS app on differnet PC (also connected to the same wifi as the PC serving the apps) so the iPad is not the issue here.
Could there be something with my local network that would be blocking the connection?
I have tried setting up the socket connection with plain socket.io client, vue-socketIO, and vue-socketIO-extended but each library had the same issue. Here is my code using vue-socketIO-extended:
main.js
import VueSocketIOExt from 'vue-socket.io-extended';
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
Vue.use(VueSocketIOExt, socket);
App.js
sockets: {
connect() {
// Fired when the socket connects.
console.log('connect')
},
disconnect() {
console.log('disconnect')
}
}
server.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:8080']
}
});
app.get('/', (req, res) => {
res.send('<h1>Hey Socket.io</h1>');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('my message', (msg) => {
io.emit('my broadcast', `server: ${msg}`);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
That's because the browser tries to connect to the WS server at http://localhost:3000, localhost resolves to IP 127.0.0.1 which is the loopback address of your device, on your iPad localhost is the iPad and there is nothing running on 127.0.0.1:3000 on the iPad.
You need to use the IP of the device that runs your server, Ex:
const socket = io('http://192.168.0.2:3000');

WebSocket Client Side Keeps reconnecting , without invoking on() events

Hello i have a nodeJs/express Server !
my socket server side :
im using https by the way.
We have Cloudflare linked too.
const server = require("http").createServer(app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('New connection', ws.url);
//connection is up, let's add a simple simple event
ws.on('message', (message) => {
//log the received message and send it back to the client
console.log('received: %s', message);
ws.send(`Hello, you sent -> ${message}`);
});
//send immediatly a feedback to the incoming connection
ws.send('Hi there, I am a WebSocket server');
});
I tried connecting to the socket on : https://websocketking.com and it worked super fine !
now I made an express app that is working with : socket.io-client
app.listen(3001, '0.0.0.0', () =>
{
console.log('App listening on 3001 !');
socket = io('https://example.com/', {path: '/notify/' , transports:['websocket'] });
socket.on("connect", (dt) => {
console.log("Connected Successfully --> ", dt);
});
socket.on('message' , (dt) => {
console.info("Got Data from Server ==> ",dt.toString());
});
socket.on('data' , (dt) => {
console.info("Got Data from Server ==> ",dt.toString());
});
});
the thing is it keeps sending New connection .. I do not know why ! Here a Screenshot from server logs :
it just keeps reconnecting ..
And none of the events are invoked !
I spent ~ 24h now with this websockets things , any help would be appreciated !
Thank you .

Socket.IO Error 400 when connecting to server, or never connects

I'm working on chat app, I have Android version made in Flutter, where Socket.IO works fine. Now I'm making web app of this chat app. But when the app tries to connect to server, the error is thrown:
WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
Here is client code (I'm using React):
console.log("Connecting to websocket...");
this.socket = io(this.serverUrl(), {
transports: ["websocket"],
autoConnect: false
});
this.socket.on("connection", (data) => {
console.log("Connected webscoket.");
this.socket.emit("join", { token: this.token });
});
this.socket.connect();
Here is server code (Node.js), (The code is not complete, of course):
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const port = process.env.PORT;
const io = require("socket.io")(http);
http.listen(port, () => {
console.info("Server is running on port " + port);
});
io.on("connection", async (socket) => {
console.log("Connected socket.io client " + socket.id);
});
socket.on("disconnect", async (reason) => {
console.log("Socket disconnected");
});
I also tried to add origins like this:
const io = require("socket.io")(http, {
origins: ["http://localhost:3001"]
});
Then the error is not there, but it never connects, and server console output looks like this:
Server is running on port 3000
Connected to database
Connected socket.io client QkoLREixPEyNglK7AAAA
Connected socket.io client QkoLREixPEyNglK7AAAA
Socket disconnected
Connected socket.io client C-j2N_Bvz8QDEQKUAAAB
Connected socket.io client C-j2N_Bvz8QDEQKUAAAB
Socket disconnected
Connected socket.io client 4Q6vxnNJb0gR-rVtAAAC
Connected socket.io client 4Q6vxnNJb0gR-rVtAAAC
Socket disconnected
Connected socket.io client g7MMXfwBuqjtS31_AAAD
Connected socket.io client g7MMXfwBuqjtS31_AAAD
Socket disconnected
Connected socket.io client NIquCegqW9yygXkIAAAE
Connected socket.io client NIquCegqW9yygXkIAAAE
...
Also the Android app stop working this way.
Thank you for all your answers.

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.

How to connect two node.js servers with websockets?

Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.

Resources