user3738290
user3738290

Reputation: 445

Websockets in NodeJS. Calling WebSocketServer from server-side WebSocket client

I have a NodeJS web app running. I have a WebSocketServer running. I can communicate with my app via a WebSocket connection made from my javascript on the client machine fine. Here's the nodejs server-side code snippet of relevance:

var WebSocket = require('ws');
var WebSocketServer = require('ws').Server;

var server = app.listen(process.env.VCAP_APP_PORT || 3000, function () {
    console.log('Server started on port: ' + server.address().port);
});

wss.on('connection', function (ws) {
    ws.on('message', function (message, flags) {
        if (flags.binary) {
            var value1 = message.readDoubleLE(0);
            var value2 = message.readInt16LE(8);
            var value3 = message.readInt8(10);

            //message.writeDoubleLE(8.5,0);

            ws.send(message, {
                binary: true
            });
        } else {
            if (message == "injest") {
                ws.send("requested: " + message);
            } else if (message == "something") {
                wss.clients[0].send('server side initiated call');
            } else {
                ws.send("received text: " + message);
            }
        }

    });

    // ws.send('something');    // Sent when connection opened.
});

So you see, all very simple.

Here 's my problem. How can I access this WebServer from the NodeJS code of the server-side app itself?

I tried the below:

var ws = new WebSocket("ws://localhost:443");

ws.on('message', function (message) {
    wss.clients[0].send('server side initiated call 1 ');
});

ws.on('close', function (code) {
    wss.clients[0].send('server side initiated call 2 ');
});

ws.on('error', function (error) {
    wss.clients[0].send(error.toString());
});

ws.send("k");

The error function is triggered with ECONNREFUSED 127.0.0.1:443.

I specified no port when I set the server up. If I do then the calls to the server from my client html page fail.

So in brief how can I set up a WebSocket client in NodeJS to access a WebSocketServer created in that app?

Upvotes: 0

Views: 2043

Answers (1)

twg
twg

Reputation: 1105

Do not use localhost. Substitute the 127.0.0.1 for it.

  1. Instantiate the Server

let WebSocketServer = require("ws").Server; let ws = new WebSocketServer({port: 9090});

ws.on('connection', function (ws) {
    console.log(nHelp.chalk.red.bold('Server WebSocket was connected.'));

    //  Add the listener for that particular websocket connection instance.
    ws.on('message', function (data) {
       //code  goes here for what you need
 });

    ws.on('close', function () {
        console.log('websocket connection closed!');
    });

});

You can open other ports and routes (example for Express) in the same file, or other ports for WS as well btw.

The above is not code for Secure WS server for TLS. that is a bit different.

Upvotes: 0

Related Questions