Connect a client to a given server using Nodejs and Socketio - javascript

I tried to write a client for a given server domain name as http://demo-chat-server.on.ag/. However, I can not connect my client to this server. My code is like this:
const io = require("socket.io-client");
const socket = io.connect("http://demo-chat-server.on.ag/", {secure: true, rejectUnauthorized: false});
socket.emit("connect", () => {
console.log(socket.connected);
});
socket.on("disconnect", () => {
console.log(socket.connected); // false
});
I received this 404 error from the console:
Can someone help me?
Also here is the task description:
task description

Related

Socket.io server not receiving custom headers send from socket.io client connection

Below is my code to make socket connection by using socket.io. The problem with the following code is I am not able to get customer header set with extraHeaders at server end. Nether socket.request.headers nor socket.handshake.headers` works for me.
const socketIO = require("socket.io-client");
const socket = socketIO('wss://domain.com', {
transports: ["websocket"],
extraHeaders: {
build_number: "227"
}
});
socket.on("connect", () => {
console.log("connected");
});

socket io client lost conection when server restarts

so I am creating a module for the members that are using my services (cloudlist.xyz).
basically, we have a voting system in our service, this module is making a connection using socket io on the server and socket io client on the module, announcing to the user when someone votes on it
Everything is working normally, but when I restart the server to do some maintenance, all users are disconnected from socket io even when the server is on again
Server side code :
var server = app.listen(process.env.PORT || 3000, () => {
console.log("Your app is listening on port " + server.address().port)
});
var io = require('socket.io')(server)
io.on("connection",function(socket) {
console.log("Someone Joined to our server api!")
})
//that's the part that he emits the event when someone votes
io.of(`vote/${bot}`).emit("voted", user_votes.val());
Module/client side:
var https = require('https');
const { EventEmitter } = require("events");
var fetch = require('node-fetch')
const io = require("socket.io-client");
module.exports = class Cloud_client extends EventEmitter {
constructor(id, token) {
super();
if (!id) throw new Error("Missing client instance on contructor");
if (!token) throw new Error("Missing token on constructor");
this.id = id;
this.token = token;
this.socket = io.connect(`https://www.cloudlist.xyz/vote/${id}`, {
reconnect:true,
autoConnect:true,
reconnectionDelay: 1000,
reconnectionDelayMax : 5000,
reconnectionAttempts: Infinity
});
this.socket.on("connect", () => this.emit("connected"));
this.socket.on("disconnect", (...args) => {this.socket.open();
});
this.socket.on("voted", (...args) => this.emit("voted", ...args));
};
this is an example of someone using the module:
var cdl = require("cloud-list")
var cloud_client = new cdl("701456902160121966","5669556617e2a070ada1688")
cloud_client.on("connected", (data) => {
console.log(`Connected to the api Server`)
})
cloud_client.on("voted", (data) => {
console.log(`Thanks,user ${data.user_name} for voting on us :)`)
})
When I connect to the server, it sends the message of this example saying "Connected to the api Server", but when I restart the server, I don't receive anything. Already tried this.socket.on("disconnect", (...args) => {this.socket.open()}); or this.socket.on("disconnect", (...args) => {this.socket.connect()}); ,but still the same thing,user can't reconnect again.
the only way for users to connect again is to restart his project, which is very bad
Socket connections require the server to be serving. Socket.io doesn't seem good for a voting system unless you want it to be real time. It's expected for clients to restart when the server restarts.
As per with working in Socket server we need to restart our node socket server during the restart of the main servers like apache or Nginx.
Because it is not an automatic process on the server.

Socket IO namespace not working with Express

I have tried setting up a namespace on the backend,
const server = require("http").createServer(app);
const connectedUsers = {};
const io = require("socket.io")(server, {
path: "/socket",
serveClient: false,
// below are engine.IO options
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
const singularConnection = io.of("/singular-socket");
singularConnection.on("connection", socket => {
console.log("unique user connected with socket ID " + socket);
}
And on my client, I try connecting with,
const socket = io(GATEWAY, {
path: "/socket/singular-socket",
transports: ["websocket"],
jsonp: false
});
socket.connect();
socket.on("connect", () => {
console.log("connected to socket server");
});
I've tried different variation of the URL, getting rid of /socket and moving other stuff around, but I can't seem to get it working. What am I doing wrong here?
I don't have any experience in using socket.io, but from the docs...
To connect to a namespace, the client code would look like.
const socket = io('http://localhost/admin', {
path: '/mypath'
});
Here, the socket connects to the admin namespace, with the custom path
mypath.
The request URLs will look like:
localhost/mypath/?EIO=3&transport=polling&sid= (the namespace is
sent as part of the payload).
Following the above lines, your code should look like..
const socket = io("http://localhost/singular-socket", {
path: "/socket",
transports: ["websocket"],
jsonp: false
})
Where /singular-socket is the namespace and /socket is the path.
Try this repl

ReactNative Socket.IO : "SocketRocket: In debug mode. Allowing connection to any root cert"

Trying to connect using socket.io-client, with no success.
Not much information about this topic out there, most examples are using localhost...
When using a network sniffer (Charles) to try and trace request, I can see normal HTTP requests, and ReactNative localhost server (When running debug) but do not see my socket connect URL. It does not even trigger.
Receiving this warning on chrome debugger:
"SocketRocket: In debug mode. Allowing connection to any root cert"
Code:
import Client from "socket.io-client";
const url = "wss://mydomain.general.green/engine.io/?transport=polling&b64=1&token=235353423343"
const socketIOConnOpt = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 10000,
"reconnectionDelayMax": 60000,
"reconnectionAttempts": "Infinity",
"timeout": 10000,
"transports": ["websocket"]
};
const socket = new Client(url, socketIOConnOpt);
socket.on("connect", () => {
Log.info("Connected to socket");
});
socket.on("event", (event) => {
Log.info("Event from socket" + event);
});
socket.on("disconnect", () => {
Log.info("Disconnected to socket");
});
socket.on("message", (message) => {
Log.info("Socket message" + message);
});
Running on an iOS simulator.

Socket.io only successfully connects if window opens before server starts

I've been trying to resolve a really strange Socket.io bug.
If I open the page on the client while the server is running, it will fail to connect with the message:
universalModuleDefinition:3 WebSocket connection to
'ws://localhost:4000/socket.io/?EIO=3&transport=websocket&sid=f6LwPIDZubiPKE-TAAAA'
failed: Connection closed before receiving a handshake response
If I then restart the server, while leaving the page open, it connects without issue.
app.js
const app = express();
const server = require('http').Server(app);
require('./socket')(server);
// More code here
server.listen(app.get('port'))
socket.js
const io = require('socket.io');
const jackrabbit = require(`jackrabbit`);
const rabbit = jackrabbit(process.env.RABBIT_URI);
const exchange = rabbit.default();
function Socket (app) {
this.io = io(app);
this.io.on('connection', socket => {
socket.emit('sync');
socket.on('room', room => {
socket.join(room);
});
})
this.queue = exchange.queue({ name: 'worker.socket' });
this.queue.consume(this.onMessage.bind(this), { noAck: true });
}
Socket.prototype.onMessage = function (message) {
this.io.to(message.report).emit('photo', message.photo);
}
module.exports = function (app) {
return new Socket(app);
}
client
var socket = io.connect();
socket.on('connect', function () {
// This gets triggered every time (after the error above)
console.log('Connected');
// This is never logged by the server
socket.emit('room', value); // value set by template engine
});
socket.on('sync', function(){
// will not execute first time I connect, but if I restart
// the server, it runs no problem
alert('Synced with server');
})
socket.on('photo', function(data) {
// also will not be run the first time, but works if the
// server is restarted when the page is open
})
Edit:
I've tried rewriting it to
Initialise socket.io within app.js, then pass it to the socket controller
Run server.listen before requiring socket.js
Initialising the client after a timeout
Setting the transport method on the client strictly to websocket
None of these methods have worked
Found the solution to my problem (actually not an issue with any of the code I posted). I was using the compression middleware for Express, which appears to break socket.io. Solution was to add the following:
app.use((req, res, next) => {
// Disable compression for socket.io
if (req.originalUrl.indexOf('socket.io') > -1) {
return next();
}
compression()(req, res, next);
});

Categories