37

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?

4
  • 1
    Like @Brad mentioned your question is client sided. For Serverside I would recommend Socket.io, which also has some sample code up. Both server and client sided
    – Templum
    Apr 9, 2017 at 20:05
  • 1
    Thanks @Templum. I have worked briefly on Socket.io I want to learn WebSockets.
    – kshikhar
    Apr 9, 2017 at 20:23
  • 1
    Make sure you are running the code in the browser and not in NodeJS, also use a modern browser that supports it
    – Omri Luzon
    Apr 9, 2017 at 20:25
  • @OmriLuzon but I want to implement it on client side - AngularJS.
    – kshikhar
    Apr 9, 2017 at 20:32

5 Answers 5

46

Try

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

Then

npm i ws

and retry. It's work with my case

2
  • 1
    Thanks. Nice tip!
    – Blue Smith
    Apr 11, 2020 at 18:29
  • 1
    This one combined with the accepted one should be the final answer.
    – Qiang Yao
    Jan 27, 2021 at 1:10
17

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

3
  • 1
    It seems like @stomp/stompjs is not the only package with a missing dependency on Websocket. In my case it was fast-xml-parser (or one of its dependencies).
    – romor
    Apr 23, 2022 at 6:47
  • Thank you for this. This solution works even in vs code plugin development. May 15, 2022 at 8:15
  • Guess when importing: import WebSocket from "ws"; Object.assign(global, { WebSocket: WebSocket }); Dec 10, 2023 at 22:49
4

When you are trying to run JavaScript, usually, you run it either in Browser or in NodeJS.

Browser and NodeJS are different JavaScript runtime.

WebSocket itself is a application layer protocol, you need to use API to employ it.

Currently(05-Dec-2019),

most browsers support WebSocket API for developer to use WebSocket.

NodeJS does not provide any OOTB API for developer to use WebSocket, you need 3rd lib to use WebSocket (e.g. https://github.com/websockets/ws).

The example you followed is using WebSocket API in browser.

Hope it helps.

2

The code you're referencing in your question is client-side code. WebSocket is available directly in browsers.

For your Node.js server-side code, look at the ws NPM package.

So, how to implement WebSockets (client side) on NodeJS?

You don't. Node.js is server-side, not client-side.

9
  • 2
    He can still use it to connect as a client, he just needs the right module for that
    – Omri Luzon
    Apr 9, 2017 at 20:07
  • @OmriLuzon Obviously, but that's not really the question though, despite the way it's worded. The error message clearly indicates that the person asking tried to run client-side code with Node.js on the server.
    – Brad
    Apr 9, 2017 at 20:10
  • Okay, your answer makes sense. So foolish of me. But if I were to use it on client side (AngularJS) then how to make it work? @Brad
    – kshikhar
    Apr 9, 2017 at 20:14
  • 1
    @kshikhar Not if you use it in a modern browser, it won't.
    – Brad
    Apr 10, 2017 at 4:00
  • 2
    @kshikhar As I said in my answer, server-side, use ws.
    – Brad
    Apr 10, 2017 at 20:26
0

If you are getting this error on your Browser console, it is important to check the spelling and capitalization. Make sure that "WebSocket" starts with capital letter. Otherwsie, it could throw reference error.

let ws = new WebSocket("ws://localhost:8080")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.