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?
Try
const WebSocket = require('ws');
var socket = new WebSocket('ws://localhost:3000');
Then
npm i ws
and retry. It's work with my case
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With