Autoconnect option in socket.io client - node.js

I my app I use socket.io. Inside the client code I use
let socket;
const connect = () => {
let error = null;
socket = io({autoConnect: false});
socket.on('connect', () => {
console.log('Connected');
});
socket.on('disconnect', (reason) => {
console.log(`Disconnected: ${error || reason}`);
error = null;
});
socket.on('message', (message) => {
$("#messages").append(message + '<br/>');
let last = document.querySelector('#messages').lastElementChild;
last.scrollIntoView();
});
socket.open();
}
But it looks like that `enter code here
socket = io({autoConnect: false});
So not work well. Every time I open the side from node server, node reports a connection. Is there a problem in my syntax? I assume that the auto connect will avoid this case so the connection is only done when call connect().

I think
socket = io({autoConnect: false, reconnection: false});
is the solution

Related

How to fix Error: listen EADDRINUSE while using nodejs isn't working, what else can I do?

I know this question was asked already, but the solutions provided didn't work for me.
Here is the websocket server code
const https = require('https');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
let connectionsList = [];
/*
*/
var server = https.createServer({
cert: fs.readFileSync(path.resolve(__dirname, '../cert/certificate.crt')),
key: fs.readFileSync(path.resolve(__dirname, '../cert/private.key'))
}, function (request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
wsServer = new WebSocket.Server({ server });
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('connection', function (connection) {
//save new connections here
connectionsList.push(connection);
connection.on('message', function (message) {
const data = JSON.parse(message) || null;
if (data !== null && data.type === 'push') {
connectionsList.forEach((connection, index) => {
//Must Skip First Item This One Pumps Data To The Others
if (index > 0) {
if (connection.state === 'closed') {
ConnectionsList.splice(index);
}
connection.send(JSON.stringify(data.message));
}
})
}
});
});
wsServer.on("error", function(err){
console.log(err);
});
module.exports = server;
Here is the runner or starter
// A simple pid lookup
var exec = require('child_process').execFile;
const wss = require('./ws_server/wss');
const config = require('./config');
var fun = function () {
const process = exec(`${config.EXE.PATH}/${config.EXE.NAME}`, function () {
wss.close();
fun();
});
//if process is created, then makea websocket server
if (process.pid != null && process.pid !== undefined) {
try{
wss.on('error', function(error){
console.log(error);
});
wss.listen({port: config.PORT,host: config.HOST}, function () {
console.log((new Date()) + ` Server is listening on port ${config.PORT}`);
});
}
catch(err){
}
}
}
fun();
I keep having this error below even after I have checked and can't find anything using that port. I have tried all the approached mentioned from the here
How to fix Error: listen EADDRINUSE while using nodejs?
but nothing seems to work for me, please can anyone explain to me what's really the problem here. I am using windows server to run this nodejs script. thanks
How to fix Error: listen EADDRINUSE while using nodejs?
The issue is that the close is not awaited since:
wss.close is called
fun is executed in sync and the wss.listen execute before the closing has been completed
It should be necessary to run fun in the close callback
const process = exec(`${config.EXE.PATH}/${config.EXE.NAME}`, function () {
wss.close(function(){
// now the server is closed
fun();
});
});
I found the problem. It was a guess.
I updated the Node.js version in the computer and after that Node connected to the port and to the db successfully

i used socketio in my nodejs app and my server slows down sometimes and sometimes it does not respond and sometimes it automatically reloads

i am building a Management App with Nodejs, Expressjs, MongoDB and Reactjs. i used socketio for realtime-ness. before using socektio, my app works fine i.e. it responds every request i made to my Nodejs API. when i used socketio, it slows down i.e. sometimes it does not respond to my queries or sometimes it automatically reloads and sends request from Client to Server. it does not show any errors. please help me to solve this issue. i have to deploy this system by next week and not getting how to solve this.
i made a separate file socket.js in which
let io;
module.exports = {
init: httpServer => {
io = require("socket.io")(httpServer, { wsEngine: "ws" });
return io;
},
getIO: () => {
if (!io) {
throw new Error("Socket is not initialized");
}
return io;
}
};
in my nodejs starting app index.js, i use this like this.
mongoose
.connect("mongodb://localhost/QuickResponse")
.then(() => {
console.log("Connected to MongoDB...");
const port = process.env.PORT || 5000;
const server = app.listen(port, () =>
console.log(`Listening on port ${port}...`)
);
const io = require("./socket").init(server);
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => {
console.log("Client is disconnected");
});
});
and whenever i want to use this in my other files, i use like this,
const io = require("../socket");
const complaint = await Complaint.findById(req.params.id);
if (!complaint)
return res.status(404).send("Complaint with given ID was not found.");
const admin = await Admin.findOne().limit(1);
complaint.assignedTo = {
_id: admin._id
};
complaint.assigned = false;
await complaint.save();
io.getIO().emit("complaints", {
action: "drop",
complaint: complaint
});
res.status(200).send("You have successfully dropped responsibility");
and on the frontend i have used socketio-client.
where i use like this.
import openSocket from "socket.io-client";
const socket = openSocket("http://localhost:5000", { reconnection: true });
socket.on("complaints", data => {
if (data.action === "new complaint") {
this.createNewComplaint(data.complaint);
toast.info(
`New Complaint has been registered with title "${
data.complaint.title
}"`
);});
i don't want my server to slow down or do not respond to my queries

NodeJS net module - don't try to create another instance of TCP server when called again

I'm totally new to the whole nodeJS asynchronous-y callback-y programming so I need more like a guidance to understanding what I'm even doing. With that said, I have two files main.js and server.js
My main file looks like this:
var server=require('./server.js');
server();
function WhenUserClicksButton(){
server();
}
and my server file looks like this:
var net = require('net');
function server(){
net.createServer(function (socket) {
socket.write('\x16'); //SYN character
socket.on('data', function (data) {
//handle data from client
});
}).listen(33333);
}
First call of server(); starts the TCP server. Then function WhenUserClicksButton is called when user clicks button (duhh) in a GUI. But it attempts to start the server again so I get
Error: listen EADDRINUSE :::33333
I got why this is happening but I can't think of a solution for it. What I really need is:
Start the server and listen on 33333
When nothing is happening server and client just exchanges SYN and ACK characters every few seconds (I already have this part done, I just removed it from this example for clarity because it's not really topic of this question)
When user click button change socket.write('\x16'); to socket.write('something');
Then wait for server and client to exchange data and after everything is done return results back to main.js
As I said, I'm new to this and I believe my problem lies in not understanding fully of what I'm doing. Any help and explanations are welcome!
I think you're very near where you need to be. I would do something like this:
server.js
var net = require('net');
var netServer = null;
var netSocket = null;
function sendData(data) {
if (netServer && netSocket) {
console.log('Send data: sending: ', data);
netSocket.write(data);
}
}
function startServer(){
netServer = net.createServer(function (socket) {
netSocket = socket;
socket.write('\x16'); //SYN character
socket.on('data', function (data) {
console.log('Server: data from client: ', data);
if (data.length === 1 && data[0] === 0x16) {
// log and ignore SYN chars..
console.log('SYN received from client');
} else if (newDataCallback) {
newDataCallback(data);
};
});
});
console.log('Server listening on 33333..');
netServer.listen(33333);
}
var newDataCallback = null;
function setNewDataCallback(callback) {
newDataCallback = callback;
}
module.exports = {
sendData: sendData,
startServer: startServer,
setNewDataCallback: setNewDataCallback
};
main.js
var server = require('./server');
function newDataCallback(data) {
console.log('newDataCallback: New data from server: ', data);
}
server.setNewDataCallback(newDataCallback);
server.startServer();
function wheneverUserClicksButton() {
server.sendData('something');
}
testClient.js
var clientSocket = net.createConnection(33333, "127.0.0.1");
clientSocket.on('data', (someData) => {
console.log('Data received', someData);
});
clientSocket.on('connect', () => {
console.log('Client Socket connected ');
clientSocket.write('Hello from client');
});

Auto Detect NodeJS application without Port number dependency

I have two applications A and B in Node Js and application B wants to communicate with application A.
Now Application A selects its port dynamically during run time. So how Application B can discover on which Port application A is running?
You can handle an event in app A and app B for ECONNREFUSED before starting your server in express which will take care of the port in used.if you see this error then just change the port number dynamically which will be true for both apps.
I did some more research and came up with solution which is "dns-discovery" and "openport"
First Check which port is open in your system using "openport" and then use "dns-discoverry".
Application A
var op = require('openport');
op.find(
{
startingPort: 8050,
endingPort: 8999
},
function (err, port) {
if (err) { console.log(err); return; }
console.log('opened port is:::::::::' + port);
ServerStart(port);
}
);
function ServerStart(port) {
var discovery = require('dns-discovery');
var disc = discovery();
disc.announce('connect-apps', port, function () {
console.log("announcement start")
});
var io = require('socket.io')(port);
io.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log("Response From Client::::::::::::" + msg);
socket.send("Congratulations from Server");
});
socket.on('disconnect', function (msg) {
console.log("We are disconnected");
});
})
}
Application B
var discovery = require('dns-discovery')
var disc = discovery()
disc.lookup('connect-apps', function () {
console.log('Server Lookup Started:::::::::::::::::::')
})
disc.on('peer', function (name, peer) {
console.log("Server found:::::::::" + peer.host + ':::' + peer.port);
var ws = 'ws://' + peer.host + ':' + peer.port;
var socket = require('socket.io-client')(ws, { forceNew: true });
socket.io.opts.transports = ['polling', 'websocket'];
socket.on('connect', function () {
console.log('connected');
socket.send('Hello from Client 1::::::::Vishal Shori Machine');
});
socket.on('message', function (msg) {
console.log("response again::::::::::::" + msg);
});
disc.destroy();
})
For Reference :
https://www.npmjs.com/package/openport
https://github.com/mafintosh/dns-discovery

Node.js net events don't fire

I have the following example of listening to connection and data events, to echo the result back to other telnet clients listening on port 8888. My telnet sessions connect to locahost fine, but no output is echoed. I am hitting my head against a brick wall trying to figure out what is wrong. The execution doesn't even get as far as the 'connect' event.
/server.js
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join', function (id, client) {
this.clients[id] = client;
this.subscriptions[id] = function (senderId, message) {
if (id != senderId) {
this.clients[id].write(message);
}
}
this.on('broadcast', this.subscriptions[id]);
});
var server = net.createServer(function (client) {
var id = client.remoteAddress + ':' + client.remotePort;
console.log(id);
client.on('connect', function () {
console.log('A new connection was made');
channel.emit('join', id, client);
});
client.on('data', function (data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
I then run in the command line
node server.js
telnet 127.0.0.1 8888
When the callback to net.createServer is called, that's because of an implicit connection event. So your code should look like this:
var server = net.createServer(function (client) {
// when this code is run, the connection has been established
var id = client.remoteAddress + ':' + client.remotePort;
console.log('A new connection was made:', id);
channel.emit('join', id, client);
client.on('data', function(data) {
...
});
client.on('end', function() {
...
});
});
The manual has this to say;
net.createServer([options], [connectionListener])
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.
In other words, your function (client) { already received the connection event, and adding a listener to it when it has already been dispatched has no further effect.

Resources