NodeJS websocket server on Plesk doesn't answer - javascript

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.

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

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

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

nodeJS socket.io on Raspberry Pi doesnt seem to be working

I am new to nodeJS...and programming. But I have tried to get this bit of code to work and I cannot understand why it does not seem to work. Whats worse is I do not know how to troubleshoot it either. If I use console.log statements, I can see that once I launch the webpage, it DOES connect, but the webpage never gets a message from the nodeJS server and the server never gets a message from the webpage. I am using Chrome browser.
server.js:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(80);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var SerialPort = require('serialport');
var portName = process.argv[2];
var sp = new SerialPort(portName, {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
io.sockets.on('connected', function (socket) {
socket.emit('connected', {
data: 'connected'
});
socket.on('connected', function (data) {
console.log(data);
//Code
console.log('Sending Packet. Contents:');
sp.write(packet);
console.log(packet);
console.log('Packet Sent');
});
});
I launch it from command prompt on raspbery pi zero w:
sudo node server.js /dev/ttyACM0
The index.html references the interface.js. The top part of interface.js:
$(document).ready(function() {
// Connect to the node.js server. Gets server's local ip.
// Using this method robot can only be connected to on
// local network.
var ip = location.host;
var socket = io.connect(ip); // Connects to server
// Upon establishing a connection to the socket.io server...
socket.on('connected', function (data) {
console.log(data);
// Send out a message to the server
socket.emit('connected', { command: 'nothing' });
});
When I have console.log statements in the interface.js I get them until the socket.on statement.
node -v
v6.4.0
npm -v
5.3.0
npm list socket.io
socket.io#2.0.3
uname -m
armv6l
Edit: Updated messaging commands. Same issue. Also
Well, turns out I have the wrong version of socket.io.js. So. That was a week of learning. Thanks for the help.

WebSocket not working with Nexe

I have built a NodeJS application and I am using Websocket to send events to Browser. Now I need to bundle the Node Application into EXE and send to client.
I tried nexe and JXCore but nexe is bundling the application but giving issue when i am trying to run it.
The JS code for Websocket is
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(1337, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
eze.ee.on("EPIC_VALIDATING_DEVICE" , function() {connection.sendUTF('VAlidate')});
The Exception stack is as follows
nexe.js:15318
wsServer = new WebSocketServer({
^
TypeError: WebSocketServer is not a function
at Array.__dirname.call.C:\Users\Raghav Tandon\WinPos\BrowserIntegrat
ion\js\RestImpl.js.http (nexe.js:15318:12)
at initModule (nexe.js:29:11)
at nexe.js:31:64
at Array.__dirname.call.C:\Users\Raghav Tandon\WinPos\BrowserIntegrat
ion\js\RestWS.js../RestImpl (nexe.js:48:20)
at initModule (nexe.js:29:11)
at Array.forEach (native)
at nexe.js:39:8
at nexe.js:46:4
at NativeModule.compile (node.js:945:5)
at Function.NativeModule.require (node.js:893:18)
Why this is not loading Webscocket module? I have tested the application as node start and it is working properly.
This is happening because of Nexe is not able to support native modules. Rather I tried Electron which works like a charm and has support for Native modules as well.

Open port 23 to read data using Node.js

On my windows laptop there is a program with a TCP/IP server on port 23. I can open it with a telnet terminal and see the data streaming. I need to get that data into a node.js program I'm working on. Should be easy but I haven't found any code examples. Searches come up with lots of examples of how to make a server on port 23 with Node.js.
Thanks
This is a high level TCP/IP socket implementation in node. See: Node net API
var net = require('net'),
port = 23,
host = 'localhost',
socket = net.createConnection(port, host);
socket
.on('data', function(data) {
console.log('received: ' + data);
})
.on('connect', function() {
console.log('connected');
})
.on('end', function() {
console.log('closed');
});

Categories

Resources