Creating wss socket with ws npm library - error: socket hang up - javascript

Is there a way in which I can create and connect to a websocket server that has accepts wss rather than just ws in the path?
I am currently using the ws npm library to do something like:
const wss = new WebSocket.Server({port: 8080});
wss.on('connection', () => {
console.log('connected!');
});
Then connecting in terminal:
wscat -c ws://localhost:8080
I would connect successfully and get the correct log message.
However I am wanting/needing to connect to a wss websocket, but cannot get this to work with the ws npm library.
wscat -c wss://localhost:8080
This returns the error: error: socket hang up
Is there some way around this at all?

You need to open a HTTPS server, in order to connect to it.
This is also explained in the documentation of ws.
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const server = https.createServer({
cert: fs.readFileSync('/path/to/cert.pem'),
key: fs.readFileSync('/path/to/key.pem')
});
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
server.listen(8080);
WS with HTTPS
You can create certificates with Let's Encrypt

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

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.

Simple example on how to use Websockets between Client and Server

I am new to websockets and just trying to get a handle of how to listen to a message from a client browser from the server and vice-versa.
I'm using a Node.js/Express setup and just want to be able to firstly listen for any messages from the client.
I've been looking at this https://github.com/websockets/ws library and have tried the examples but am not able to get this working within my localhost environment.
I'm also not clear what I need to look out for, when I'm listening for a message.
What code do I use on the client, i.e. url + port and what code do I use on the server?
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost/path', {
perMessageDeflate: false
});
Using websockets directly might be troublesome, it's advised you use a framework to abstract this layer, so they can easily fallback to other methods when not supported in the client. For example, this is a direct implementation using Express js and Websockets directly. This example also allows you to use the same server for HTTP calls.
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
//connection is up, let's add a simple simple event
ws.on('message', (message) => {
//log the received message and send it back to the client
console.log('received: %s', message);
ws.send(`Hello, you sent -> ${message}`);
});
//send immediatly a feedback to the incoming connection
ws.send('Hi there, I am a WebSocket server');
});
//start our server
server.listen(3000, () => {
console.log(`Server started on port ${server.address().port} :)`);
});
For the client, you can do something like this:
const ws = new WebSocket('ws://localhost:3000')
ws.onopen = () => {
console.log('ws opened on browser')
ws.send('hello world')
}
ws.onmessage = (message) => {
console.log(`message received`, message.data)
}
Like i have mentioned above, it is advised that you use a mature framework for websockets. Should your app be minimal and not need scaling, you can use any open source library, with socket.io being the most popular.
However, if you are talking about implementing this to be used at production level, you should know that the open source solutions do not allow for scalability, failover, message ordering etc. In that case, you’ll have to implement a realtime platform as a service tool.
Just a note, socket.io is a backend/frontend library that uses websocket but also has a number of fallbacks if the client browser does not support websocket. The example below works with ws backend.
Server
const WS = require('ws')
const PORT = process.env.PORT || 8080
const wss = new WS.Server({
port: PORT
}, () => console.log(`ws server live on ${PORT}`))
const errHandle = (err) => {
if(err) throw err
}
wss.on('connection', (socket) => {
console.log('something connected')
socket.send('you are connected', errHandle)
socket.on('message', (data) => {
console.log(`socket sent ${data}`)
socket.send('message received', errHandle)
})
})
client (browser)
(() => {
const ws = new WebSocket('ws://localhost:8080')
ws.onopen = () => {
console.log('ws opened on browser')
ws.send('hello world')
}
ws.onmessage = (message) => {
console.log(`message received ${message}`)
}
})()
edit: oh, and ws and http are different protocols. you will need a different server to serve your http files

Access Node-Red websocket listener

My server has embedded node-red. I'm trying to create new websocket listener in server. But when execute this code, websockets in node-red application stops working.
const WebSocket = require('ws');
const wss = new WebSocket.Server({
server: server,
path: '/test'
});
wss.on('connection', function connection(ws, req) {
console.log('test');
});
Websocket in node-red admin panel:
Problem is related to:
https://github.com/websockets/ws/issues/381
How access to node-red websocket and handle messages for own path?
I know this is an old thread but I thought I'd throw in that you can use the OP code in node red like this:
var WebSocket = global.get('ws');
const wss = new WebSocket.Server({
server: <your http(s) server>,
path: '/'
});
wss.on('connection', function connection(ws, req) {
node.warn('connection');
});
You just need to:
npm install ws
edit settings.js
under functionGlobalContext: add
ws:require('ws')
It does work, I'm using it like this because I couldn't get the websocket node to work in my configuration.

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