This article will share with you how to use node. js to implement multi-room chat code based on socket. io + express. It is very practical and can be referenced by partners who need it.
Socket. io Introduction
Socket. IO is an open-source WebSocket library that implements the WebSocket server through Node. js and also provides the client JS library. Socket. IO supports event-based Real-time bidirectional communication, which can work on any platform, browser, or mobile device.
Socket. IO supports four Protocols: WebSocket, htmlfile, xhr-polling, and jsonp-polling. It automatically selects the appropriate communication mode based on the browser, so that developers can focus on the implementation of functions rather than the compatibility of the platform, at the same time Socket. IO has good stability and performance.
Multi-room chat
Socket. io provides APIs for rooms and namespace
Multi-room chat can be implemented using the rooms API. The following is a summary: join/leave room and say to room.
// Join and leaveio. on ('connection', function (socket) {socket. join ('some room'); // socket. leave ('some room') ;}); // say to roomio. to ('some room '). emit ('some event'): io. in ('some room '). emit ('some event '):
Code github
Create a folder chatapp-demo
Chatapp-demo/package. json
{ "name": "chatapp-demo", "version": "1.0.0", "description": "multi room chat app demo, powered by socket.io", "main": "app.js?6.1.3", "dependencies": { "express": "^4.13.3", "hbs": "^3.1.0", "path": "^0.11.14", "socket.io": "^1.3.6" }, "devDependencies": {}, "author": "wuyanxin", "license": "ISC"}
Run npm install
Server code
Added the chatapp-demo/app. js file.
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 ('view', path. join (_ dirname, 'view'); app. set ('view engine', 'bosc'); // create the socket service var socketIO = IO (server); // The room username list var roomInfo ={}; socketIO. on ('connection', function (socket) {// obtain the url of the request to establish a socket connection // For example: http://localhost:3000/room/room_1 , RoomID is room_1 var url = socket. request. headers. referer; var splited = url. split ('/'); var roomID = splited [splited. length-1]; // obtain the room ID var user = ''; socket. on ('join', function (userName) {user = userName; // Add the user nickname to the room list if (! RoomInfo [roomID]) {roomInfo [roomID] = [];} roomInfo [roomID]. push (user); socket. join (roomID); // join the room // notify the staff in the room of socketIO. to (roomID ). emit ('sys ', user +' added to the room ', roomInfo [roomID]); console. log (user + 'added' + roomID) ;}); socket. on ('Leave ', function () {socket. emit ('disconnect') ;}); socket. on ('disconnect', function () {// remove var index = roomInfo [roomID] from the room list. indexOf (user); if (index! =-1) {roomInfo [roomID]. splice (index, 1);} socket. leave (roomID); // exit socketIO. to (roomID ). emit ('sys ', user +' exited the room ', roomInfo [roomID]); console. log (user + 'exited' + roomID) ;}); // receives user messages and sends the corresponding room socket. on ('message', function (msg) {// verify that if the user is not in the room, if (roomInfo [roomID] is not sent. indexOf (user) ===- 1) {return false;} socketIO. to (roomID ). emit ('msg ', user, msg) ;}); // room pagerouter. get ('/room/: roomid', function (req, res) {var roomID = req. params. roomID; // render page data (see views/room. harvard) res. render ('room ', {roomID: roomID, users: roomInfo [roomID]}) ;}); app. use ('/', router); server. listen (3000, function () {console. log ('server listening on port 3000 ');});
Client code
Added chatapp/views/room. Harvard.
{RoomID }} Nickname:
Room: {roomID }}
Current number of online users: {users. length }}
Online users:{Users }}
Press Enter to sendExit the room