简体   繁体   中英

Connecting a WebSocket to a WebSocketServer in NodeJS

I have a simple novice question which I hope somebody can help me with:

I have a NodeJS app and an HTML page with some JavaScript on it deployed in CloudFoundry.

In the app.js server-side NodeJS code I start a WebSocket Server as below:

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

var wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: true
});

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);

            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);
            }
        }

    });
});

I can call this WebSocketServer successfully from my client-side JavaScript as for example:

function OnWebSocketConnectionMessage(event) {
    alert(event.data);
}

this.m_parent.m_WebsocketConnection = new
WebSocket('wss://MyWebSpace.MySiteURL');

this.m_parent.m_WebsocketConnection.onmessage =
    OnWebSocketConnectionMessage;

this.m_parent.m_WebsocketConnection.send(this.m_parent.m_editbox1.value);

This works fine.

I now try to call this WebSocketServer from my server-side NoeJS code as below:

var ws = new WebSocket("wss://MyWebSpace.MySiteURL");

if (ws == null) {
    res.send("null");
} else {
    res.send(ws.readyState.toString());
}

But I get the result '0' which is of course CONNECTING The connection is not yet open.

And it never does. Can anyone please suggest any help?

(If I add port:9090 (or any other port number) to my server creation parameters then my client-side WebSocket creation fails).

Thanks, Mitch.

No worries,

I solved it.

Mitch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM