Koa & WebSocket inAction_WebSocketKoa & WebSocket inAction socket.io-client socket.io



Koa & WebSocket inAction

node.js

 ​

ping / pong

socket.io

  1. client send ​​2​​ as ​​ping​
  2. server response ​​3​​ as ​​pong​

Koa & WebSocket inAction_WebSocket

 

# WebSocket sever
$ yarn add socket.io

$ npm i socket.io


Koa & WebSocket inAction_Koa_03

 ​

// 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


Koa & WebSocket inAction_WS_04

 ​


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(){});


 

Koa & WebSocket inAction_TCP_05

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