Realization of multi-room chatting based on socket.io+express _node.js

Source: Internet
Author: User
Tags emit

Socket.io Introduction

Socket.io is an open source WebSocket library, which realizes WebSocket server by Node.js and also provides client JS library. Socket.io supports event-based, real-time two-way communication, which can work on any platform, browser, or mobile device.

Socket.io supports 4 protocols: WebSocket, Htmlfile, xhr-polling, jsonp-polling, which automatically chooses the appropriate means of communication based on the browser, allowing the developer to focus on the implementation of the feature rather than the compatibility of the platform. At the same time, Socket.io has good stability and performance.

Multi-room Chat

Socket.io provides rooms and namespace APIs

With rooms API can realize many room chat, summed up no outside is: Join/leave room and say to room

Join and 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 '):

Code GitHub
Create a new 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 ",
 " dependencies ": {
  " Express ":" ^4.13.3 ",
  " HBS ":" ^3.1.0 ",
  " path ":" ^0.11.14 ",
  " Socket.io ":" ^1.3.6 "
 },
 " Devdependencies ": {},
 " author ":" Wuyanxin ",
 " license ":" ISC "
}

Perform NPM Install

Service-side code

Add File Chatapp-demo/app.js

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 ');
Create the socket service var socketio = IO (server);

Room user list var roominfo = {}; Socketio.on (' Connection ', function (socket) {//Get request to establish a socket connection URL//such as: Http://localhost:3000/room/room_1, Roomid for Roo
 m_1 var url = socket.request.headers.referer;
 var splited = url.split ('/');  var roomid = splited[splited.length-1];

 Get 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//inform the room staff socketio.to (roomid). Emit (' sys ', user + ' joined 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].indexof (user) from the list of rooms;
  if (index!==-1) {Roominfo[roomid].splice (index, 1);  } socket.leave (Roomid);
  Exit Room socketio.to (Roomid). Emit (' sys ', user + ' exit Room ', Roominfo[roomid]);
 Console.log (user + ' quit ' + roomid);

 }); Receive user messages, send corresponding room socket.on (' message ', function (msg) {//Verify if the user is not in the room, do not send if (roominfo[roomid].indexof) = 1
  ) {return false;
 } socketio.to (Roomid). Emit (' msg ', user, msg);

});

});

 Room page router.get ('/room/:roomid ', function (req, res) {var roomid = Req.params.roomID;
Render page data (see 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 ');};

Client code

Add Chatapp/views/room.hbs

<! DOCTYPE html>  

Add chatapp/public/index.html

<! DOCTYPE html>  

Run effect

Code has been placed in GitHub Https://github.com/wuyanxin/chatapp-demo.git

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.