Web development & API design

L012: Real-time updates with Web Sockets

HTTP (REST)

Client must request something from server

Pre-standard

Enter WebSockets

WebSockets + Node.js

const app = require('express')();

const server = app.listen(3456, function () {
    console.log('Server listening on port ' + 3456);
});

require('./sockets').connect(server);
const ws = require('ws');

exports.connect = httpServer => {
    const wsServer = new ws.Server({
        server: httpServer,
    });

    wsServer.on('connection', socket => {
        socket.send('Hello, sockets!');
    });
};

sockets.js

regular server file

Simple client: wscat

"cURL for WS"

Important functions

  • wsServer.on('connection', socket => { ... });

Not a lot!

(Demo: echo server)

socket.send('some message');

socket.on('message', message => { ... });

"Broadcast"

const clients = [];

wsServer.on('connection', socket => clients.push(socket));

const broadcast = message => {
    clients.forEach(client => client.send(message));
};
  1. Maintain a list of connected clients
     
  2. Iterate and send <message> to all

WebSockets and React

constructor() {
 super();

 this.state = {
  messages: []
 }
}

componentWillMount() {
 const url = 'ws://localhost:3456';
 const connection = new WebSocket(url);

 connection.onopen = () => console.log('WebSocket opened!');

 connection.onmessage = message => {
  const text = JSON.parse(message.text);
  this.setState({
   messages: [...this.state.messages, text],
  }};
}

...

(Demo: simple messaging app)

Demo

Time

Yay

Exercise

  1. Make a simple webpage with four coloured boxes
     
  2. When a box is clicked, set the page's background colour to that colour
     
  3. When any client clicks a box, update everyone's background colour

PG6300-17-012 Realtime updates with WebSockets

By theneva

PG6300-17-012 Realtime updates with WebSockets

  • 747