Multi-room chat and socket. ioexpress Based on socket. io + express

Source: Internet
Author: User

Multi-room chat and socket. ioexpress Based on socket. io + express

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", "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 ('connect Ion ', 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.

<! DOCTYPE html> 

Added chatapp/public/index.html

<! DOCTYPE html> 

Running Effect

Code has been placed on github https://github.com/wuyanxin/chatapp-demo.git

Articles you may be interested in:
  • Detailed steps for installing express and configuring the app. js file in the nodejs tutorial
  • Socket. io entry instance in node. js
  • Build an instant communication system based on socket. io and node. js
  • Socket. IO instance in node. js
  • Advanced use of Socket. IO in node. js
  • Node + express + ejs simple page Getting Started Guide
  • Explanation of express middleware bodyParser
  • How to Use socket. io in node express
  • Use Angular, Nodejs, and socket. io to set up chat rooms and multi-user chat rooms

Related Article

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.