Socket.IO是一個開源的WebSocket庫,它經過Node.js實現WebSocket服務端,同時也提供客戶端JS庫。Socket.IO支持以事件爲基礎的實時雙向通信,它能夠工做在任何平臺、瀏覽器或移動設備。
Socket.IO支持4種協議:WebSocket、htmlfile、xhr-polling、jsonp-polling,它會自動根據瀏覽器選擇適合的通信方式,從而讓開發者能夠聚焦到功能的實現而不是平臺的兼容性,同時Socket.IO具備不錯的穩定性和性能。html
socket.io提供rooms和namespace的API
用rooms的API就能夠實現多房間聊天了,總結出來無外乎就是:join/leave room 和 say to roomnode
// join和leave io.on('connection', function(socket){ socket.join('some room'); // socket.leave('some room'); }); // say to room io.to('some room').emit('some event'): io.in('some room').emit('some event'):
新建文件夾chatapp-demochatapp-demo/package.json
jquery
{ "name": "chatapp-demo", "version": "1.0.0", "description": "multi room chat app demo, powered by socket.io", "main": "app.js", "dependencies": { "express": "^4.13.3", "hbs": "^3.1.0", "path": "^0.11.14", "socket.io": "^1.3.6" }, "devDependencies": {}, "author": "wuyanxin", "license": "ISC" }
執行 npm install
git
增長文件 chatapp-demo/app.js
github
var express = require('express'); var path = require('path'); var IO = require('socket.io'); var router = express.Router(); var app = express(); var server = require('http').Server(app); app.use(express.static(path.join(__dirname, 'public'))); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); // 建立socket服務 var socketIO = IO(server); // 房間用戶名單 var roomInfo = {}; socketIO.on('connection', function (socket) { // 獲取請求創建socket鏈接的url // 如: http://localhost:3000/room/room_1, roomID爲room_1 var url = socket.request.headers.referer; var splited = url.split('/'); var roomID = splited[splited.length - 1]; // 獲取房間ID var user = ''; socket.on('join', function (userName) { user = userName; // 將用戶暱稱加入房間名單中 if (!roomInfo[roomID]) { roomInfo[roomID] = []; } roomInfo[roomID].push(user); socket.join(roomID); // 加入房間 // 通知房間內人員 socketIO.to(roomID).emit('sys', user + '加入了房間', roomInfo[roomID]); console.log(user + '加入了' + roomID); }); socket.on('leave', function () { socket.emit('disconnect'); }); socket.on('disconnect', function () { // 從房間名單中移除 var index = roomInfo[roomID].indexOf(user); if (index !== -1) { roomInfo[roomID].splice(index, 1); } socket.leave(roomID); // 退出房間 socketIO.to(roomID).emit('sys', user + '退出了房間', roomInfo[roomID]); console.log(user + '退出了' + roomID); }); // 接收用戶消息,發送相應的房間 socket.on('message', function (msg) { // 驗證若是用戶不在房間內則不給發送 if (roomInfo[roomID].indexOf(user) === -1) { return false; } socketIO.to(roomID).emit('msg', user, msg); }); }); // room page router.get('/room/:roomID', function (req, res) { var roomID = req.params.roomID; // 渲染頁面數據(見views/room.hbs) res.render('room', { roomID: roomID, users: roomInfo[roomID] }); }); app.use('/', router); server.listen(3000, function () { console.log('server listening on port 3000'); });
新增chatapp/views/room.hbs
express
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>{{roomID}}</title> <style> #msglog, #messageInput { border: 1px solid #ccc; width: 500px; height: 350px; overflow-y: auto; font-size: 14px; } #messageInput { height: 80px; } .message { line-height: 22px; } .message .user { padding-right: 5px; padding-left: 5px; color: brown; } .sysMsg { color: #c1bfbf; padding-right: 5px; padding-left: 5px; font-size: 12px; } #users { width: 490px; padding: 0 5px 5px; } </style> </head> <body> 暱稱: <span id="userName"></span> <br/> 房間: {{roomID}} <br/> 當前在線人數: <span id="count">{{users.length}}</span> <br/> 在線用戶: <div id="users">{{users}}</div> <div id="msglog"> </div> <textarea name="message" id="messageInput"></textarea> <br/> 按Enter鍵發送 <button id="joinOrLeave">退出房間</button> <script src="/socket.io/socket.io.js"></script> <script src="/js/jquery.js"></script> <script> $(function () { // ----------設置暱稱------------- var userName = ''; while ($('#userName').text().trim() === '') { userName = prompt("請設置你的暱稱",""); $('#userName').text(userName); } // ---------建立鏈接----------- var socket = io(); // 加入房間 socket.on('connect', function () { socket.emit('join', userName); }); // 監聽消息 socket.on('msg', function (userName, msg) { var message = '' + '<div class="message">' + ' <span class="user">' + userName + ': </span>' + ' <span class="msg">' + msg + '</span>' + '</div>'; $('#msglog').append(message); // 滾動條保持最下方 $('#msglog').scrollTop($('#msglog')[0].scrollHeight); }); // 監聽系統消息 socket.on('sys', function (sysMsg, users) { var message = '<div class="sysMsg">' + sysMsg + '</div>'; $('#msglog').append(message); $('#count').text(users.length); $('#users').text(users); }); // 發送消息 $('#messageInput').keydown(function (e) { if (e.which === 13) { e.preventDefault(); var msg = $(this).val(); $(this).val(''); socket.send(msg); } }); // 退出房間 $('#joinOrLeave').click(function () { if ($(this).text() === '退出房間') { $(this).text('進入房間'); socket.emit('leave'); var msg = '你已經退出了房間,從新發言請點擊"進入房間"'; $('#msglog').append('<div class="sysMsg">'+msg+'</div>'); } else { $(this).text('退出房間'); socket.emit('join', userName); } }); }); </script> </body> </html>
新增 chatapp/public/index.html
npm
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>demo</title> </head> <body> 歡迎您,騷年 <div> <p>房間列表</p> <ul> <li id="room_1"><a href="/room/room_1" target="_blank">1號房間</a></li> <li id="room_2"><a href="/room/room_2" target="_blank">2號房間</a></li> <li id="room_3"><a href="/room/room_3" target="_blank">3號房間</a></li> <li id="room_4"><a href="/room/room_4" target="_blank">4號房間</a></li> <li id="room_5"><a href="/room/room_5" target="_blank">5號房間</a></li> <li id="room_6"><a href="/room/room_6" target="_blank">6號房間</a></li> <li id="room_7"><a href="/room/room_7" target="_blank">7號房間</a></li> <li id="room_8"><a href="/room/room_8" target="_blank">8號房間</a></li> <li id="room_9"><a href="/room/room_9" target="_blank">9號房間</a></li> <li id="room_10"><a href="/room/room_10" target="_blank">10號房間</a></li> </ul> </div> </body> </html>
代碼已放在github https://github.com/wuyanxin/chatapp-demo.gitjson
http://socket.io/docs/rooms-and-namespaces/
http://blog.fens.me/nodejs-socketio-chat/
http://www.jianshu.com/p/d9b1273a93fd瀏覽器