客户端
import socket from 'socket.io-client';
const chat = socket('ws://127.0.0.1:3000');
chat.on('news', function (data) {
console.log(data);
chat.emit('my other event', { my: 'data' });
});
服务端
// 引得包已将 io 设为全局变量
io.on('connection', function (socket) { // 每个链接 'ws://127.0.0.1:3000' 的 socket 均会连进来
io.sockets.emit('news', { hello: 'world' }); // 触发所有连接的 socket 'news' 事件
socket.broadcast.emit('news', { hello: 'world' }); // 触发除该 socket 外所有连接进来的 socket 'news' 事件
socket.emit('news', { hello: 'world' }); // 触发该 socket 'news' 事件
socket.on('my other event', function (data) { // 监听该 socket 'my other event' 事件
console.log(data);
});
});
let chat = io.of('/news').on('connection', (socket) => { // 每个链接 'ws://127.0.0.1:3000/news' 的 socket 均会连进来
// connect usercount
usercount++
// console.log(socket)
chat.emit('usercount', { msg: usercount }) // 触发所有连接进来 usercount 事件
socket.on('messagetoserver', (data, callback) => {
socket.emit('messagetoclient', { msg: data.msg.toUpperCase(), username: 'server' })
callback('已收到')
})
// disconnect usercount
socket.on('disconnect', function () {
usercount--
chat.emit('usercount', { msg: usercount })
})
})