Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - 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 AngularJS)? What am I missing here?

like image 720
kshikhar Avatar asked Apr 09 '17 19:04

kshikhar


2 Answers

Try

const WebSocket = require('ws');
var socket = new WebSocket('ws://localhost:3000');

Then

npm i ws

and retry. It's work with my case

like image 112
PaPu Avatar answered Nov 17 '22 19:11

PaPu


I'm leaving this here for people having trouble with the @stomp/stompjs package in a node app.

Add this line:

Object.assign(global, { WebSocket: require('ws') });

also, don't forget to npm install ws

like image 13
Vlad Lego Avatar answered Nov 17 '22 19:11

Vlad Lego