Koa & WebSocket inAction socket.io-client socket.io
node.js
ping / pong
socket.io
- client send
2
as ping
- server response
3
as pong
# WebSocket sever
$ yarn add socket.io
$ npm i socket.io
// createServer()
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
Express.js
const app = require('express')();
// createServer(app)
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
Koa.js
const app = require('koa')();
// createServer(app.callback())
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
ws
# WebSocket sever
$ yarn add ws
$ npm i ws
$ npm i -S ws
WebSocket Client
# WebSocket client
$ yarn add socket.io-client
$ npm i socket.io-client
// ES6 import, ESM
import io from 'socket.io-client';
const socket = io();
// package.json
// ES5 require, CJS
var socket = require('socket.io-client')('http://localhost:3000');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
js vanilla WebSocket API
MDN
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
socket.io bug
// chat message bug ❌❓
// socket.on('chat message', (msg) => {
socket.on('message', (msg) => {
log(`chat message`, msg)
const li = document.createElement(`li`);
li.innerText = msg;
ul.append(li);
});
xgqfrms