I have a simple p2p app, but when I connect and exit as another peer or client the server stops completely. I've looked into connection.setKeepAlive, but it doesn't work they way I thought it would. I simply want the connection to any other peers to persist if another one exits.
const net = require('net')
const port = 3000
const host = 'localhost'
const server = net.createServer((connection) => {
console.log('peer connected')
})
server.listen(port, () => {
console.log('listening for peers')
})
const client = net.createConnection(port, host, () => {
console.log('connected to peer')
})
In your script the port on which the server listen is the same that you use for the client connection, so the application is calling itself.
Here is a script that connect to its peer and disconnect every 2 seconds:
const net = require('net')
const myPort = 3001
const peerPort = 3002
const host = 'localhost'
const server = net.createServer((connection) => {
console.log('peer connected')
})
server.listen(myPort, () => {
console.log('listening for peers')
})
let connectionTest = function() {
const client = net.createConnection(peerPort, host, () => {
console.log('connected to peer')
});
client.on('close', (err) => {
console.log("connection closed");
});
client.on('error', (err) => {
console.log("error");
});
//TODO do stuff
client.end();
setTimeout(connectionTest, 2000);
}
setTimeout(connectionTest, 3000);
For every instance you should change the ports (myPort & peerPort)
Related
I'm writing tests for client-side socket communication with socket.io. I'm trying to test connection and other effects that rely on the socket receiving events from the server. I tried to write a server for my jest tests, but the server doesn't start.
Here's a sample of the code:
describe('App Communication', () => {
/* Testing flags */
let hasConnected = false;
/* Create server */
const httpServer = createServer();
const sampleMessage = 'Hello world!';
const io = new Server(httpServer);
beforeAll(() => {
httpServer.listen('4000', () => {
console.log('listening on 4000');
io.on('connection', (socket) => {
hasConnected = true;
socket.emit('message', sampleMessage);
socket.on('message', (message) => {
...
});
});
});
});
...
Is there any way to get the server up and running?
httpServer.listen is asynchronous, so you need to tell Jest to wait until the server starts before running test cases:
beforeAll((done) => { // Jest will wait until `done` is called
httpServer.listen('4000', () => {
console.log('listening on 4000');
io.on('connection', (socket) => {
hasConnected = true;
socket.emit('message', sampleMessage);
socket.on('message', (message) => {
...
});
});
done();
});
});
it('should connect to socket', () => {
// Connect to localhost:4000 here
});
I am trying to setup a socket in production like so:
client :
import openSocket from 'socket.io-client';
function handleSomething() {
let socketServer = 'https://staging.app.xxx.eu:9999';
const socket = openSocket(socketServer);
socket.on('calendlyHook', () => {
console.log("*** HERE");
...
socket.emit('closeSocket');
socket.close();
socket.removeAllListeners();
});
}
server :
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
function openSocket() {
io.close();
io.set('origins', '*:*');
io.on('connection', (client) => {
console.log('Socket connected');
client.on('closeSocket', () => {
io.close();
io.removeAllListeners();
console.log('Socket closed');
});
});
const port = 9999;
io.listen(port);
console.log('*** listening on port ', port);
}
Then server-side, another function tries the following:
io.emit('calendlyHook');
or
io.sockets.emit('calendlyHook');
I have several issues in production (none of which happen on localhost):
console.log('*** listening on port ', port) is working fine
console.log('Socket connected') is not happening
io.emit('calendlyHook') or io.sockets.emit('calendlyHook') are not doing anything
I do not have any web server proxy set up on that url.
What is wrong here? Thanks!
I am facing a socket.io connection issue. I know this question is already asked many times. And I tried solutions too from those questions but none of the solution work for me.
Here is my code:
const express = require('express');
var app = express();
var server = app.listen(8000, () => console.log('3000 is the port'));
var io = require('socket.io').listen(server);
const users = {};
io.on('connection', socket => {
console.log('connection ')
if (!users[socket.id]) {
users[socket.id] = socket.id;
}
socket.emit("yourID", socket.id);
io.sockets.emit("allUsers", users);
socket.on('disconnect', () => {
delete users[socket.id];
})
socket.on("callUser", (data) => {
io.to(data.userToCall).emit('hey', {signal: data.signalData, from: data.from});
})
socket.on("acceptCall", (data) => {
io.to(data.to).emit('callAccepted', data.signal);
})
});
Where am I making a mistake?
Your server is running on 8000 port but you logged that it is running on 3000. Hence try connecting it using localhost:8000 connection url.
You can also change server to run on port 3000 instead of 8000.
const PORT=3000;
const server = app.listen(PORT, () => console.log(`${PORT} is the port`));
I've got an aedes MQTT broker and my MQTT client, but I can't seem to connect them.
In my app.js I do the following:
(async function () {
try {
await startBroker();
await mqttClient();
} catch (e) {
console.error("ERROR: ", e);
process.exit();
}
})();
My startBroker function start aedes and streams it like so:
const aedes = require('aedes')();
const server = require('net').createServer(aedes.handle);
const port = 1883;
exports.startBroker = function() {
return new Promise((res, rej) => {
server.listen(port, function () {
console.log(`MQTT Broker started on port ${port}`);
return res()
});
})
};
and then my mqttClient tries to connect, however I can never get to actually connect. I've tested it against the test mosquitto server which works fine
const mqtt = require('mqtt');
const client = mqtt.connect("mqtt://localhost:1883");
exports.mqttClient = function() {
console.log("Connecting to MQTT Client");
client.on("connect", ack => {
console.log("MQTT Client Connected!");
client.on("message", (topic, message) => {
console.log(`MQTT Client Message. Topic: ${topic}. Message: ${message.toString()}`);
});
});
client.on("error", err => {
console.log(err);
});
}
Does anyone know why my broker doesn't seem to be working?
Could you clarify, how the broker is not working and what actually works? Where and how do you run the code?
When I put the code into a single file (changing exports. into const), it does work. I had to add a semicolon after the function declaration of mqttClient, but after that, I get the following console output:
MQTT Broker started on port 1883
Connecting to MQTT Client
MQTT Client Connected!
This is the full code that can be copied right away. It runs in Node.js v12.15.0 on my macOS 10.15 Catalina.
const aedes = require('aedes')();
const server = require('net').createServer(aedes.handle);
const port = 1883;
// exports.startBroker = function() {
const startBroker = function() {
return new Promise((res, rej) => {
server.listen(port, function () {
console.log(`MQTT Broker started on port ${port}`);
return res()
});
})
};
const mqtt = require('mqtt');
const client = mqtt.connect("mqtt://localhost:1883");
//exports.mqttClient = function() {
const mqttClient = function() {
console.log("Connecting to MQTT Client");
client.on("connect", ack => {
console.log("MQTT Client Connected!");
client.on("message", (topic, message) => {
console.log(`MQTT Client Message. Topic: ${topic}. Message: ${message.toString()}`);
});
});
client.on("error", err => {
console.log(err);
});
}; // <-- semicolon added here
(async function () {
try {
await startBroker();
await mqttClient();
} catch (e) {
console.error("ERROR: ", e);
process.exit();
}
})();
this is my code for setting up mqtt broker with aedes. For settings up wss (connection with SSL) you will have to added one more configuration just like the ws part. Let me know if you need code for SSL also.
const express = require('express');
const aedes = require('aedes')();
const ws = require('websocket-stream');
const fs = require("fs");
const server = require('net').createServer(aedes.handle);
const app = express();
const ports = {
mqtt : 1883,
ws : 8080,
wss : 8081,
}
const host = '0.0.0.0' // localhost
server.listen(ports.mqtt, function () {
console.log(`MQTT Broker running on port: ${ports.mqtt}`);
});
// -------- non-SSL websocket port -------------
var wsServer = require('http').createServer(app)
ws.createServer({ server: wsServer}, aedes.handle)
wsServer.listen(ports.ws, host, function () {
console.log('WS server listening on port', ports.ws)
})
I created a simple tcp server using code
var net = require('net');
// Setup a tcp server
var server = net.createServer(function (socket) {
socket.addListener("connect", function () {
console.log('hello');
sys.puts("Connection from " + socket.remoteAddress);
socket.end("Hello World\n");
});
});
server.listen(7000, "127.0.0.1");
console.log("TCP server listening on port 7000 at 127.0.0.1");
It started successfully, but how can I send some test msg to that tcp server, I tried SocketTest v.3 but not console output.
Use data event handler to receive data in the server.
socket.on('data', function(data) {
console.log(data);
// echo back
socket.write('You said '+data);
});
For people still looking for answers, here's how I did it with SocketTest
const net = require('net');
const client = new net.Socket();
const HOST = "127.0.0.1";
const PORT = 7000;
client.on('data', () => {
client.destroy(); // kill after response
});
client.on('error', () => {
client.destroy(); // kill
});
client.connect(PORT, HOST, () => {
client.write('Hello world!');
client.end();
});