Reputation: 623
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?
Upvotes: 38
Views: 82477
Reputation: 443
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")
Upvotes: 0
Reputation: 1698
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
Upvotes: 17
Reputation: 121
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.
Upvotes: 5
Reputation: 813
Try
const WebSocket = require('ws');
var socket = new WebSocket('ws://localhost:3000');
Then
npm i ws
and retry. It's work with my case
Upvotes: 47
Reputation: 163234
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.
Upvotes: 2