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

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.

Related

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

Cannot connect to MQTT Broker from ReactJS

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.

Socket io timeout connecting to heroku socket io server with custom namespace

I'm trying to connect to my server located in heroku with socket io with this code, which works when the server is ran locally but, when I try to connect to the same server on herkoku it won't connect and it will give me a timeout.
I've tried setting transport to websocket on the client and it gives me websocket error on chrome and can't establish connection on firefox.
Client side code:
const io = require('socket.io-client');
socket = io.connect('https://herokuappurl.com:23840/custom_nsp');//not works
socket = io.connect('localhost:23840/custom_nsp');//works
Server side code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const PORT = process.env.PORT || 8000;
var server = http.listen(PORT,function(){
print('listening on *:' + PORT);
});
io.of('/custom_nsp').on('connection', function(socket) {
/*socket.on events*/
}
I downgraded to version 1.7 at it works now.

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.

Using socket io without returning the index.html throws an error

I would like to setup websocket without necessarily having to return the index.html file
Am still new to the socket io and this is what i have tried
installed socket io via
npm install socket.io --save
created index.js
var http = require('http');
var fs = require('fs');
// Loading socket.io
var io = require('socket.io');
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
});
server.listen(1100);
Now when i run node index am getting an error
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot read property 'on' of undefined
What am trying to do is connect the websocet to my vuejs client side so ive skipped the part to display html part since i dont want to display html but to use the socket events.
where am i going wrong?
Hey you need to attach socket.io to an http server for your code to work and listen to incoming events.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
//io.on is the shorter form of io.sockets.on
io.on('connection', function(socket){
console.log('user connected');
});

Categories

Resources