I need your help because i have a node js server with websocket like this :
const app = require("../app"); // Basic app file
const server = require("http").createServer(app);
const WebSocket = require("ws");
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
ws.send('message')
ws.on("close", () => {
console.log('connection closed'));
});
ws.on("message", (data) => {
console.log(data.toString());
});
});
server.listen();
And client side :
var ws = new WebSocket('wss://topicsall.fr',)
ws.onopen = function () {
console.log('open');
};
ws.onmessage = function () {
console.log('message');
};
I have no error message but the connection remains on hold and is interrupted after the elapsed time.
In dev mode I have no problem, it's only in production.
I've been stuck for 4 days, I really need your help! Thanks
Related
I have a problem only in production mode, let me explain:
I created a subdomain on which I placed a websocket as follows:
const app = require("../app"); // app.js it's OK !
const server = require("http").createServer(app);
const WebSocket = require("ws");
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
// Code is reduced for demo
console.log('New connection') // Is triggered by the client from my primary domain
ws.on("close", () => {
console.log(`Connection closed`);
});
});
server.listen()
I specify that the subdomain and the main domain are in https.
This is the client code on my main domain:
socket = new WebSocket('wss://my-subdomain.com/');
socket.addEventListener("open", () => {
console.log('Connection open'); // But it never fires
});
Does anyone know where the problem comes from? Thanks for your help !
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 have a very basic websocket server / client in JS:
Server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 3300});
wss.on('connection', function connection(ws, req) {
});
Client:
var ws = new WebSocket('wss://example.com/socket', ['appProtocol']);
I want to reject the connection with the server when the Client is not using the
'appProtocol' protocol.
I feel like this should be pretty easy, still I cant find anything and cant get it done by myself. Any help is highly appreciated, thank you!
Nvm, I found a solution that works for me:
Server:
const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({noServer: true});
wss.on('connection', (ws, req) => {
console.log('Opened Connection with URL ' + req.url.substr(1));
ws.on('close', () => {
console.log('Closed Connection with URL ' + req.url.substr(1));
});
});
server.on('upgrade', (request, socket, head) => {
if (request.headers['sec-websocket-protocol'] === 'appProtocol') {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
})
} else {
socket.destroy();
}
});
server.listen(3300);
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)
I have a uWebSockets server as it seems to be a lot more performance friendly than socket.io servers.
So I have a server and its connected fine and after some trouble I got the index.html client side to connect, but now I'm not able to push events to the server from the client side. What am I doing wrong?
var WebSocketServer = require('uws').Server,
express = require('express'),
path = require('path'),
app = express(),
server = require('http').createServer(),
createEngine = require('node-twig').createEngine;
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
ws.on('join', function (value) {
console.log('SOMEONE JUST JOINED');
});
ws.on('close', function () {
//console.log('stopping client interval');
clearInterval(id);
});
});
server.on('request', app);
server.listen(8080, function () {
console.log('Listening on http://localhost:8080');
});
index.html
<script>
var host = window.document.location.host.replace(/:.*/, '');
var server = new WebSocket('ws://' + host + ':8080');
server.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};
server.onopen = function (event) {
server.send("Here's some text that the server is urgently awaiting!");
server.send('join');
};
function something() {
console.log('WORKED');
server.send('join');
}
</script>
You don't have an event listener setup on the server side that does receive and react on the message. Like
ws.on('message', function (msg) {
// Do something with the message received from the client
});