I am working on a React frontend application and I am trying to set up a WebSocket connection to my Golang backend server.
So far I have a simple class that is supposed to initiate a websocket connection using the native websocket object. It is failing with error ReferenceError: WebSocket is not defined
export class MyService implements RealtimeService {
socket: WebSocket;
constructor() {
console.log('initializing websocket connection');
this.socket = new WebSocket('ws://localhost:50000');
this.socket.on("open", (event) => {
console.log('connection established');
});
this.socket.on("error", (event) => {
console.log('connection failed', event)
});
this.socket.on('message', (event) => {
console.log('received message from server ', event.data);
})
this.socket.on('close', (event) => {
console.log('connection closed ', event);
})
}
serviceName(): string {
//TODO: implement
return "";
}
subscribe(channelName: string): any {
//TODO: implement
return new Channel();
}
}
I have tried installing the ws
package using npm install ws
and import WebSocket from 'ws';
based on the solution from here https://stackoverflow.com/a/52037864/3083825 but it looks like the ws
package does not work on the browser anymore. It fails with error Error: ws does not work in the browser. Browser clients must use the native WebSocket object
My question is, why isn't the native WebSocket
object working? When I create a simple javascript file, the native WebSocket object works fine but it doesn't work in this react app. How can I make it work?