Websocket Basics with JavaScript

Intro

To implement WebSockets, you need a client and a server. Ws.js is a library for Node.js that lets you create servers. For the client side, we'll use the native WebSocket object in the browser.

  • Server side: ws.js WebSocket implementation
  • Client side: Native WebSocket object in browser

Server example

You need to install the ws package with npm first:

npm install ws

Here is a modified example from https://www.npmjs.com/package/ws#simple-server.

server.js:

// server.js
// npm install ws
// Run this server and then open client.html in browser
// Reference: https://www.npmjs.com/package/ws#simple-server
const { WebSocketServer } = require('ws');

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    console.log('Client sent the server: %s', data);
  });

  ws.send('Greetings, client!');
});

console.log('Running...');

Client example

This example is modified from the Mozilla docs example.

client.html:

<!-- client.html -->
<!-- https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#examples -->
<html>
<body>

<script>

    const socket = new WebSocket('ws://localhost:8080');

    // Connect
    socket.addEventListener('open', function (event) {
        socket.send('Hello Server!');
    });

    // Handle server messages
    socket.addEventListener('message', function (event) {
        console.log('Message from server ', event.data);
    });

    // To send data, use `socket.send()`

</script>

</body>
</html>

References

Advertisement