Hairi
Hairi

Reputation: 3715

npm 'websocket' server send message to client

In the code that I inherited is used this websocket. I read the documentation and did a lot of google search to find how websocketServer can emit message to the client(browser). Here is a code snippet:

    var wsServer = new WebSocketServer({
        httpServer: server,
        autoAcceptConnections: false,
        path:"/async" //This attribute is not in the documentation
    });

  wsServer.on('request', function(request) {
    var connection = request.accept('relay_protocol', request.origin);
    connection.on('message', function(message) {
       ....
       });
     });

I wasnt able to find documentation for connection object. What propety does it have?

And last, what method to use to send message back to the client?

In general the information given for this module is very poor. Please help.

Upvotes: 0

Views: 2191

Answers (1)

Tamas Szoke
Tamas Szoke

Reputation: 5542

The full documentation for this module is here.

From their example (server):

connection.on('message', function(message) {
    if (message.type === 'utf8') {
        console.log('Received Message: ' + message.utf8Data);
        connection.sendUTF(message.utf8Data);
    }
    else if (message.type === 'binary') {
        console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        connection.sendBytes(message.binaryData);
    }
});

So these both sends a message to the client:

connection.sendUTF(message.utf8Data);

connection.sendBytes(message.binaryData);

I hope this helps!

Tip: try out the socket.io module.

Upvotes: 1

Related Questions