WebSocket
https://github.com/websockets/ws
https://github.com/websockets/ws/blob/master/doc/ws.md
npm install ws
Sending and receiving text data
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', () => {
ws.send('something');
});
ws.on('message', (data) => {
console.log(data);
});
Simple server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (message) => { /* ... */ });
ws.on('close', () => { /* ... */ });
ws.send(/* ... */);
});
Use with Express.js
const app = require('express')();
const server = require('http').createServer(app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
app.get('/', (req, res)=> {
res.sendFile(/* ... */);
})
wss.on('connection', (ws) => {
ws.on('message', (message) => { /* ... */ });
ws.on('close', () => { /* ... */ });
});
server.listen(/* port */, () => {
/* ... */
});
Client-side
<script>
const ws = new WebSocket(`ws://${location.host}`);
ws.onopen = function() { /* ... */ };
ws.onmessage = function(event) { /* ... */ };
ws.onclose = function() { /* ... */ };
</script>
https://www.runoob.com/html/html5-websocket.html