該聊天室基於socket.io實現客戶端與服務器雙工實時通訊。該聊天室能夠發送消息、圖片、文件。node
客戶端git
1. 建立客戶端並鏈接服務器 localhost:3000 var socket = io('localhost:3000') 2. 向服務器發送事件 //發送用戶名 socket.emit("join", name) //發送消息 socket.emit("message", userObj) //發送文件、圖片 socket.emit('base64 file', msg); 3. 監聽服務器發來的事件 socket.on("join", function (user) { socket.name = user addLine(user + '加入了羣聊') }) //接收到服務器發來的message事件 socket.on("message", function(msg) { addLine(msg) }) socket.on('disconnect', function(msg){ addLine(msg + '退出了羣聊'); }) socket.on('base64 file', function(msg){ addLine(msg) })
服務器github
1.監聽客戶端發來的鏈接事件 io.on('connection', function(socket){} 2. 監聽客戶端發來事件,並將該事件發送給全部客戶端 //鏈接客戶端 io.on('connection', function(socket){ console.log('a user connected') //socket捕獲join事件 socket.on("join", function (name) { socket.name = name; usocket\[name\] = socket //服務器將join事件發送給全部客戶端 io.emit("join", name) }) socket.on("message", function (msg) { io.emit("message", msg) //將新消息廣播出去 }) socket.on('disconnect', function(msg){ io.emit('disconnect', socket.name); }) socket.on('base64 file', function (msg) { socket.username = msg.username; // socket.broadcast.emit('base64 image', //exclude sender io.sockets.emit('base64 file', //include sender msg ); }); });
node server
demoshell