42

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 Commented Apr 9, 2017 at 20:05
  • 1
    Thanks @Templum. I have worked briefly on Socket.io I want to learn WebSockets. Commented 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 Commented Apr 9, 2017 at 20:25
  • @OmriLuzon but I want to implement it on client side - AngularJS. Commented Apr 9, 2017 at 20:32

5 Answers 5

49

Try

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

Then

npm i ws

and retry. It's work with my case

Sign up to request clarification or add additional context in comments.

1 Comment

This one combined with the accepted one should be the final answer.
18

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 Comments

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).
Thank you for this. This solution works even in vs code plugin development.
Guess when importing: import WebSocket from "ws"; Object.assign(global, { WebSocket: WebSocket });
5

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.

Comments

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 Comments

He can still use it to connect as a client, he just needs the right module for that
@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.
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 Not if you use it in a modern browser, it won't.
@kshikhar As I said in my answer, server-side, use ws.
|
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")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.