Cannot connect to MQTT Broker from ReactJS - javascript

I'm facing issues while connecting to my local MQTT Broker running in docker.
Here is my connection file:
import mqtt from 'mqtt';
const client = mqtt.connect({
host: 'ws://192.168.31.46',
port: 1883,
});
client.on('connect', () => {
console.log('Connected');
client.subscribe('SEND_MESSAGE', function (topic, message) {
console.log({ topic, message });
});
});
export default client;

The port number is (99.9%) wrong, port 1883 is the native MQTT port not MQTT over WebSockets. What the correct port is will depend on how you have configured the broker (Assuming mosquitto, it does not have a WebSocket listener defined by default)
Also if the mqtt.connect() function is asking for a hostname and port then you shouldn't be give a URL to the post field. Remove the ws:// from the start.

Related

Why is my socket io not connecting? Problem with connection io

When starting my server I get the console.log from the listen, but not the console.log from the socket io connection with socket id
import express from "express";
import dotenv from 'dotenv';
import http from 'http';
import { Server } from 'socket.io';
dotenv.config();
const app = express();
const PORT = process.env.PORT;
const httpServer = http.createServer(app);
const io = new Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connection is ready!", socket.id);
})
httpServer.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
On my console it is just returned to me
Server is running on port 3009
The server-side 'connection' event is supposed to be the event fired when a Socket.io client connects to such server. Moreover, the socket object passed to the event callback is the client socket object. So you won't see the 'connection' callback executed until a socket client tries to connect. Here you can find more info about how to set up a socket client with Socket.io.
If you need to better understand how websockets work take a look here.

Websocket client not connecting to server (nodejs)

I have a NodeJS express app which listens on port 3000. In that app I define a websocket connection like so:
const express = require('express');
const app = express();
const server = require("http").createServer(app);
const WebSocket = require("ws");
const wss = new WebSocket.Server({ server });
wss.on("connection", ws => {
ws.send("You (the client) connected");
ws.on("message", msg => {
ws.send("Server received your msg: " + msg);
});
});
app.listen(3000, () => {console.log("Listening on port 3000");});
This code is on the NodeJS backend, and it listens for websocket connections. It sends a message to the client when the client connects, and when the client sends a message.
On the font end, I have the following vanilla JavaScript code inside my index.html:
const socket = new WebSocket("ws://my.url.com:3000");
socket.addEventListener("open", evnt => {
console.log(evnt);
socket.send("Меssage from client");
});
socket.addEventListener("message", evnt => {
console.log("Received msg from server:", evnt.data);
});
But my code does not work: when I run the front-end code, the socket object (in the front end) never connects; when I try to call socket.send I get an error:
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Eventually the connection times out but the client socket never connects to the socket on the server. How can I fix my code so that the client side can connect successfully?
You can use socket.readyState to check what state the server is in.
There are four possible states: CONNECTING, OPEN, CLOSING, or CLOSED. So if you used a function like this:
window.setInterval(function() {
if(socket.readyState == 'OPEN') {
//send while open
}
}, 500)
Then that should do the trick. Read more about it here

Javascript: Can I open websocket server connection at random port

I want to create webserver socket connection at random port. And I want to return server port to calling application or just print it in terminal.
The typical code to create a server connection is as below.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 0 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
So I am trying to create server at port 0. I assume it will create server at random port. How do I get that random port?
I want to know the port number, as soon as server socket is created.
Now I am able to create the websocket server at random port and able to get the port number as well. Not sure if it is the right way, but it works.
const http = require('http');
const WebSocket = require('ws');
const url = require('url');
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection(ws) {
console.log(wss);
});
server.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
});
server.listen(0, '127.0.0.1', function incoming() {console.log (server.address().port);});
Websocket works with http/s on port 80 or 443. The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

What does socket remote port represent?

http-client.js:
const http = require('http');
http.get
(
{
port : 9001,
host : 'localhost'
},
(res) =>
{
//...
}
);
tcp-server.js:
const net = require('net');
let server = new net.Server();
server.listen(9001, 'localhost', (err) =>
{
console.log('Started listening', server.address());
});
server.on('connection', (sock) =>
{
console.log(`Connected ${sock.remoteAddress}:${sock.remotePort}`);
});
I run node tc-server.js and then when I run node http-client.js I see output like:
Started listening { address: '127.0.0.1', family: 'IPv4', port: 9001 }
Connected 127.0.0.1:59506
I close http-client.js and run node http-client.js again. I see: Connected 127.0.0.1:59508
I close server and run again, and run the client again, I see Connected 127.0.0.1:59510
So the socket.remotePort is increasing all the time. What I don't understand is why those numbers for ports, I was expecting to see 9001 for port number since that's where the http request was being sent and successfully reached the listening tcp server.
Both sides of a TCP conversation have to have an address and a port. E.g., clients use ports too. What your console.log was telling you was that the client connected to your port 9001 using its port 59506. When your server sends packets to the client, it addresses them with the client's address and that port number, so the TCP layer of the network stack on the client knows what process to send the packet to. (More in the Wikipedia article on TCP.) You see the number increasing just as a byproduct of how your client system assigns available ports to connections.
You don't normally need to care about the client's port.

NodeJS websocket server on Plesk doesn't answer

I am new to NodeJS and I have just set up a subdomain to work with it on my Plesk Onyx 17.5.3 server.
I have done a simple websockets chat app but it doesn't work.
If I start the app via command line doing:
node server/server.js
the app works flawlessly. The code in server.js is:
"use strict";
process.title = 'node-chat';
const WebSocketServer = require('ws').Server;
const PORT = 9000;
const wss = new WebSocketServer({port: PORT});
console.log('WSS');
let messages = [];
wss.on('connection', function (ws) {
console.log('WS connection');
messages.forEach(function(message){
ws.send(message);
});
ws.on('message', function (message) {
messages.push(message);
console.log('Message Received: %s', message);
wss.clients.forEach(function (conn) {
conn.send(message);
});
});
});
wss.on('error', function(obj){
console.log('WS error');
console.log(obj);
});
console.log((new Date()) + 'server.js started');
If I start the application using Plesks "Restart app" it doesn't work. Doing a ps aux I can see the process is working. In the log file I see it has started:
App 17579 stdout: WSS
App 17579 stdout: Fri Jul 28 2017 13:52:44 GMT+0200 (CEST)server.js started
But there is no log saying websocket server has started or crashed, it just doesn't work. If I try to connect a client side js app to the server gives an error saying it can't connect to the server:
WebSocket connection to 'ws://server_address:9000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
Any clues?
Thanks!
May I ask where you found the Nodejs logs on Plesk? And how are you able to get to the console on plesk?
As an answer to your question:
It could be that the port you provided is not configured to allow traffic from the web to your node application. That's why I'd recommend using
var port = process.env.PORT || 9000;
This line will try to use the port that could be configured in an object containing the user environment data.

Categories

Resources