使用koa和socket.io简单搭建多人聊天流程

koa与socket.io简单流程分析:

1. 服务端触发初始化io.on('connection', socket => {});
2. 客户端发送say会话socket.emit('say', '我是客户端'); 
3. 服务端监听say会话socket.on('say',data => {}); 
4. 服务端发送message会话socket.emit('message', {hello: '你是谁'});
5. 客户端接收message消息socket.on('message', (data) => {});

服务端:

const koa = require('koa');
const app = new koa();
const server = require('http').Server(app.callback())
const io = require('socket.io')(server);
const port = 8081;

server.listen(process.env.PORT || port, () => {
    console.log(`app run at : http://127.0.0.1:${port}`);
})

io.on('connection', socket => {
    console.log('socket初始化完成');
    socket.on('say', data => {
        console.log(data, '接收到的信息')
        socket.emit('message', {hello: '你是谁'})
    })
})

客户端




  
  Document
  


  

你可能感兴趣的:(node.js,websocket,socket.io,koa2)