Make Node.js websocket client run indefinitely - javascript

I'm using ws library to handle Websocket connections client-side.
Here's example from ws docs (https://github.com/websockets/ws#usage-examples):
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
The problem is that this program exits after receiving just the first message from server.
How do I make it run and listen for messages indefinitely?

Related

Why is a connection not created for this simple websocket snippet?

I have a simple snippet on the front end as follows which I can verify is working. I can do this by changing the port to something other than 3000 and it will error.
It is definitely finding the server at that port:
// Create WebSocket connection .. will error if I change the port
const socket = new WebSocket('ws://localhost:3000');
console.log('DEBUG: Web socket is up: ');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
I am using ws-express on the server side as follows. This was the minimal example given in the NPM docs:
const expressWs = require('express-ws')(app);
app.ws('/echo', (ws, req) => {
ws.on('message', (msg) => {
ws.send(msg);
});
});
However, the open event on the client never fires. I would like to send messages from the client to the server, but I assume, that I need an open event to fire first.

Communicating between Lua and NodeJS using WebSockets not working

I am making a control panel for my Minecraft mining turtle and I need to communicate between the two using websockets. I have troubleshooted the Lua side of things and that works as intended when I connected it to a echo server.
Code here:
local ws,err = http.websocket("wss://localhost:5757")
if ws then
ws.send("Hello")
print(ws.receive())
ws.close()
end
However, I can not get the NodeJS side to work. I have tried different ports, I've tried opening ports.
Code here:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5757 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('testing 123');
});
I can't figure out where I have gone wrong. All help is appreciated.
EDIT: Thought I'd add that it's not giving errors either, that I am using the ws npm package and running the latest LTS node version.
EDIT 2: I tried this code example here
const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org/');
ws.on('open', function open() {
ws.send('testing 123');
});
ws.on('message', function incoming(data) {
console.log(data);
});
And it worked and replied with 'testing 123' so it seems that the web socket doesn't want to run on local host.

creating websocket server in electron node for external client request

I am trying to create a websocket server that listen to an external websocket clinet.
the point is I am laoding a web base application inside my browser window in electron.
for example : win.loadURL(www.something.com); so the websocket call coming from this url
meaning if I getinto this url in browser in my network tab I see websocket call is keep
calling but there is no server. so I want to implement the server inside my electron app main.js. and here is my code:
const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 8102});
wss.on("connection", ws => {
ws.on("message", message => {
console.log("received: %s", message);
});
ws.send("something");
});
so far I did not get any success. any help would appriciate.
you need to start your http server
mine looks like this:
import http from "http";
import * as WebSocket from "ws";
const port = 4444;
const server = http.createServer();
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws: WebSocket) => {
//connection is up, let's add a simple simple event
ws.on("message", (message: string) => {
//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(port, () => {
console.log(`Data stream server started on port ${port}`);
});

How to call a function from outside the object

I am trying to make a proxy between sockets and websockets. I receive requests on socket server and I want to proxy them to websocket clients, however websocket.ws.send appears to be undefined. What would be the correct way of doing this? How to call ws.send() from outside of the object?
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8001}),
var net = require('net')
websocket = wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send("NEW USER JOINED");
});
var socketServer = net.createServer(function(socket) {
socket.on("data", function(data){
console.log("Received: "+data)
websocket.ws.send("Message")
});
});
socketServer.listen(1337, '127.0.0.1');
The problem you have is that ws is a single web socket for one connection. It is not a property on the websocket object, but an argument to a callback you define. Each time someone connects you will get a connection event which will execute your callback, allowing you to bind a function to that specific web socket for the message event.
You either need to store the ws object in a variable that the socket server can access or you could broadcast to all clients.
wss.clients.forEach(function each(client) {
client.send(data);
});
This will work fine if you only have one client, however if you have multiple connections to both the websocket and socket server then you need to use a method of identifying connections on both so that you can locate the websocket connection you need to send data to.

websockets - ws with node

I'm trying to push messages from server to client using ws module in node.js application.
Please find below the code in app.js.
var server = app.listen(port);
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({ server: server});
wss.on('connection', function (ws) {
console.log('connected');
});
ws.on('message', function (data, flags) {
});
});
code in the client side js file.
window.WebSocket = window.WebSocket || window.MozWebSocket;
var host = window.document.location.host.replace(/:.*/, '');
var port = window.document.location.port;
var socketConnection = new WebSocket('ws://'+ host+':'+ port);
socketConnection.onerror = function (error) {
// TODO : report error here..
};
socketConnection.onmessage = function (message) {
var obj = JSON.parse(message.data)
};
The problem is when i'm running the node application locally.i.e http://localhost:port and when I try to handshake with ws connection through "ws://localhost:port\". The handshake happens and i am able to send and receive messages.
But when i access the same application using the ip of my machine i.e as http://10.xx.yy.zz:port. Im able to open the application and do evrything but the handshake with websockets time out. The same happens when the app is running in another machine and i try to connect to it from my machines browser.The handshake doesnot happen and it times out.
I have tried the same with demos provided out of box by ws module. The same happens. Am I missing something when creating the websocket server?

Categories