L012: Real-time updates with Web Sockets
Client must request something from server
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
"cURL for WS"
Not a lot!
(Demo: echo server)
socket.send('some message');
socket.on('message', message => { ... });
const clients = [];
wsServer.on('connection', socket => clients.push(socket));
const broadcast = message => {
clients.forEach(client => client.send(message));
};
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)