WebSocket Client Side Keeps reconnecting , without invoking on() events - node.js

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 .

Related

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.

How to display client's data on the terminal using node.js and web sockets

const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8082 });
wss.on("connection", (ws) => {
console.log("New client connected!");
ws.on("message", (data) => {
console.log("Client has sent us: ${data}");
});
//ws.send(data.toUpperCase());
ws.on("close", () => {
console.log("Client has disconnected!");
});
});
Here, the message displays on the dev tools network panel under the localhost. But, in the node terminal, it displays as Client has sent us: ${data} while the expected result to be Client has sent us: Whatever the message sent by the client.
I will attach the screenshot of the terminal herewith. Thanks in advance.Image of the terminal

Not able to connect to nodeJS socket.io server on localHost using flutter client

i'm trying to stabilish a connection between a nodeJS server and a flutter app but I always receive connect_error on client side. If I try to connect by the browser, it's successful, so i think the problem is on client side.
My nodeJS server:
const app = require('express')()
const http = require('http').createServer(app)
var io = require('socket.io')(http)
io.on('connection', (client) => {
console.log('a user connected')
client.on('message', (data) => {
console.log('Message received --> ', data)
// io.emit('chat', data)
})
})
http.listen(5000, () => {
console.log('Listening on port 5000')
})
Client side is implemented using socket_io_client package on InitState as follows:
import 'package:socket_io_client/socket_io_client.dart' as IO;
IO.Socket socket;
#override
void initState() {
//on xxx.xxx.xxx.xxx i'm inserting my local ip address
socket = IO.io('http//xxx.xxx.xxx.xxx:5000/', <String, dynamic>{
'transports': ['websocket']
});
socket.connect();
socket.on("connect", (_) => print('Connected'));
socket.on("connect_error", (data) => print('connect_error: ' + data));
super.initState();
}
The client keeps showing the output "connect_error: timeout".
Anybody can help? Thanks in advance.
Edit1: Also tried to disable windows firewall but it didn't help.

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

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);
});

Socket.io (emit, on) not working - Node JS

I am working on a node JS application, where I am trying to use socket.io following this tutorial. Until this tutorial everything is fine, even the client is connected to the server through the socket, as it display a message on connection. But I don't know why my code isn't working on emit, and on event, and event handler.
Below is my Code on server side :
const express = require("express");
const app = express();
const scrap = require("./algorithm");
const mysql = require("mysql");
const ms_connect = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'scrapper_db'
});
const server = app.listen(8000, function(){ console.log('Listening on 8000'); });
const io = require("socket.io").listen(server);
app.use(express.static(__dirname + "/"));
io.on("connection",function(socket){
console.log("Sockets Connection Made ! " + socket.id);
socket.emit("testing",{data:"I am tested"});
io.on("disconnect",function(){
console.log("Client Disconnected !");
})
})
//mySQL Conection
ms_connect.connect(function(err){
if(err) console.log(err);
ms_connect.query("Select * FROM test",function(err,rows,fields){
if(err) console.log("Error Executing Query");
})
})
app.get("/scrap",function(req,res){
res.sendFile(__dirname+"/index.html");
})
Client side code :
var socket = io.connect('http://localhost:8000/scrap');
console.log(socket.connected); //returns false :(
socket.on("testing", function(d) {
console.log(d);
});
In the client side, the socket.connected object returns false, but on server side it says connected. I don't know how , and
I am using third link from this socket.io cdnjs server.
You are doing io.connect('http://localhost:8000/scrap') but the scrap is not mentioned anywhere on the server side. It should be io.connect('http://localhost:8000/'). Pointing to your HTML file is not needed because the socket.io server and your webserver are unrelated.
Also as pointed out by #TommyBs you should use
socket.on('connect', () => { console.log(socket.connected); });
to check if you are connected because connecting is asynchronous so it will not have connected yet by the time you do console.log(socket.connected);
The whole client code would be
var socket = io.connect('http://localhost:8000');
socket.on('connect', () => { console.log(socket.connected); });
socket.on("testing", function(d) {
console.log(d);
});
Change http://localhost:8000/scrap to http://localhost:8000/ in the client code. You're connecting to the wrong route.

Resources