Websockets have a lot in common with https. In fact, they start their lives as https connections and then get upgraded to persistent websocket connections.
So, your client (Javascript in your browser) initiates a connection using an instance of the WebSocket object. Then it can send and receive messages to and from the server. Your browser code might look like this. It initiates a connection. When the connection opens it sends a message.
const ws = new WebSocket("ws://www.example.com:8090/socketserver");
ws.onmessage = function (event) {
console.log ('incoming', event.data);
}
ws.onopen = function (event) {
ws.send ("Hey there server!");
}
On the server (nodejs) side you need to rig up a websocket server to accept your client connections. You can do this with npm's ws package. (There are other packages, but I known this one works.)
Your minimum viable ws server code is pretty simple too.
const WebSocket = require('ws');
...
const wss = new WebSocket.Server({ port: 8090 });
wss.on('connection', function connection(ws) {
/* Here an incoming websocket connection is accepted
* You must keep the ws object in scope for the lifetime
* of the connection */
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
/* respond to ping keepalives from client */
ws.on('ping', function ping() {
ws.pong();
}
/* send messages as needed */
ws.send('hey there client!');
});
Notice this: browser security doesn't allow you to mix connection modes (https / http) from browsers to servers. So if the rest of your front end is served via https:, you'll need to use wss: instead of ws:. It's a little harder to rig on the server side, but still works the same way.
Also notice that I haven't given any error or timeout handling. Production code needs those things.