- 服务端
监听服务器建立连接和断开连接
io.on('connection', socket => { console.log('a user connected!'); //disconnect socket.on('disconnect', () => { console.log('a user disconnected!'); }) }
向全体人员广播
io.sockets.emit(自定义参数,data);
向全体人员广播
io.emit(自定义参数, data);
发送信息
socket.emit(自定义参数,data)
接收信息
socket.on(自定义参数,callback)
用户断开连接触发事件
socket.on('disconnect',callback);
信息传输对象为排除当前socket 对应的 client 的其他client
socket.broadcast.to(socketId ).emit('msg', msg)
向某房间发送消息
io.to(roomId).emit('event name', { // some data })
加入/离开房间
// join room socket.join(roomId); // leave room socket.leave(roomId);
服务端代码
const express = require('express'); const app = express(); const http = require('http'); const server = http.createServer(app); // Express 初始化app可以提供给HTTP服务器的函数处理程序 const { Server } = require("socket.io"); const io = new Server(server); // socket.io自动为我们服务客户端传递server(HTTP 服务器)对象来初始化 的新实例。然后我监听connection传入套接字的事件并将其记录到控制台 app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); let roomInfo = {}; let users = []; io.sockets.on('connection', socket => { socket.on('disconnect', () => { console.log(`客户端断开链接`) }) socket.on('login', user => { if (-1 != users.indexOf(user)) { return false; } users.push(user) io.sockets.emit('login', user) io.sockets.emit('updateUserList', users) }) socket.on('chat', data => { console.log(data, 'data') io.sockets.emit('chat', data) }) socket.on('creatGroup', data => { if (!(data.roomId in roomInfo)) { roomInfo[data.roomId] = data; } io.sockets.emit('creatGroup', data.roomId) }) }) server.listen(3000, () => { console.log('listening on *:3000'); });
- 客户端
socket.emit(自定义参数,data) //发送信息
socket.on(自定义参数,callback//接收信息
部分js代码
<script src="/socket.io/socket.io.js"></script> <script> socket = io.connect(); //登录 loginDom.addEventListener('click', () => { let user = userDom.value.trim(); if (!user) { alert('用户名为空') return } socket.emit('login', user, 1) }) // 创建群组 creatGroupDom.addEventListener('click', () => { let user = userDom.value.trim(); let group = { user, roomId: `room_id_${(Date.now())}` } socket.emit('creatGroup', group) }) // 监听创建群组 socket.on('creatGroup', data => { creatGroupDom.innerHTML = `<dt>群组列表</dt>` }) //服务器连接提示 socket.on('connect', () => { addMsg(roomNoticeDom, `服务器连接成功`) }) //登录 socket.on('login', (user) => { addMsg(roomNoticeDom, `${user}进入房间`) document.getElementById('user').disabled = true; }) //更新用户列表 socket.on('updateUserList', users => { userListDom.innerHTML = `<dt>用户列表</dt>` // userListDom.removeChild(ddDom) for (let user of users) { let dd = document.createElement('dd') dd.innerText = user; userListDom.appendChild(dd) } }) //监听消息 socket.on('chat', (data) => { console.log('接收到消息') var item = document.createElement('li'); item.style.background = '#ff0' item.textContent = `${data.user}说:${data.message}`; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight + 30); }) //发送消息 form.addEventListener('submit', (e) => { e.preventDefault(); if (message.value) { console.log(message, user, '发送信息成功') socket.emit('chat', { message: message.value, user: userDom.value.trim() }) } message.value = ''; }) </script>
- 预览