Sunday, 9 April 2017

NodeJS - ReferenceError: WebSocket is not defined

Focusing on the client side API only (because each server side language will have its own API), the following snippet opens a connection, creates event listeners for connect, disconnect, and message events, sends a message back to the server, and closes the connection using WebSocket.

// Create a socket instance
var socket = new WebSocket('ws://localhost:3000');

// Open the socket
socket.onopen = function(event) {

    // Send an initial message
    socket.send('I am the client and I\'m listening!');

    // Listen for messages
    socket.onmessage = function(event) {
        console.log('Client received a message',event);
    };

    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed',event);
    };

    // To close the socket....
    socket.close()

};

But I am getting an error on executing above snippet:

ReferenceError: WebSocket is not defined

I have gone through various links like https://davidwalsh.name/websocket, on how to implement WebSockets. But none of them are importing any npm package.

Question: So, how to implement WebSockets (client side) on NodeJS? What am I missing here?



via kshikhar

No comments:

Post a Comment