HTML5 websocket + node. JS Implements web chat rooms

Source: Internet
Author: User
Tags emit

1 Client:socket.io

Server:node.js + Express + Socket.io

A simple chat room demo, no registration, built-in some test users

2 Client key Code

varSocket = Io.connect (' http://localhost:8080 '); Socket.on (' Connect ',function() {Console.log (' Connected to server '); Socket.on (' Login Success ',function(data) {Console.log (' Login Success '); Username=Data.username;    Refreshonlineusers (data.allusers);            }); Socket.on (' Disconnect ',function() {Console.log (' Disconnect '); Username=NULL;        }); Socket.on (' Login failed ',function() {username=NULL;        }); Socket.on (' New message ',function(data) {Console.log (' Receiver message from ' +data.fromuser + ' +data.date+ ' +data.msg);            }); Socket.on (' Update Myself ',function(data) {}); Socket.on (' Enter chat ',function(data) {Console.log (Data.username+ ' has entered the chat ');    Refreshonlineusers (data.allusers);        }); Socket.on (' Leave chat ',function(data) {Console.log (Data.username+ ' has leaved the chat ');    Refreshonlineusers (data.allusers); });});

3 Server Key Code

varExpress = require (' Express ');varApp =Express ();varServer = require (' http '). Server (app);varIO = require (' Socket.io ') (server); App.use ('/', express.static (__dirname + '/www '))); varUsers ={fanglin:{socket:NULL, Online:false}, xingtianyu:{socket:NULL, Online:false}};io.on (' Connection ',function(socket) {Socket.on (' New message ',function(data) {varI,user; Socket.emit (' Update myself ', {fromuser:data.fromuser,msg:data.msg,date:NewDate ()}); if(data.broadcast===true) {Socket.broadcast.emit (' New message ', {fromuser:data.fromuser,msg:data.msg,date:NewDate ()}); }Else{             for(i=0;i<data.tousers.length;i++) {User=Users[data.tousers[i]]; if(user.online==true&& user.socket!=NULL) {User.socket.emit (' New message ', {fromuser:data.fromuser,msg:data.msg,date:NewDate ()});        }            }        }    }); Socket.on (' Login ',function(data) {if(Data.usernameinchusers) {Users[data.username].online=true; Users[data.username].socket=socket; Socket.emit (' Login Success ', {username:data.username,allusers:getonlineusers ()}); Socket.broadcast.emit (' Enter chat ', {username:data.username,allusers:getonlineusers ()}); }Else{socket.emit (' Login failed ');        }    }); Socket.on (' Disconnect ',function(){        varuser;  for(Userinchusers) {            if(Users[user].socket = =socket) {Users[user].online=false; Socket.broadcast.emit (' Leave chat ', {username:user,allusers:getonlineusers ()}); return; }        }    });}); Server.listen (8080); Console.log (' Server is listenering on port 8080 ');

4 realization of a simple finite state machine

(1) When the client starts to connect to the server, the connection successfully triggers the connection event on the service side

(2) After the successful connection, the client can log in, triggering the login event on the server, the server to find the user, if the login successful server sends login success message to the client, and returns all the online users, and sends the Enter Chat broadcast to the other online users, Login failed to send login failed message to client.

(3) The client can send a message to other online users after a successful login, the client sends a new message to the server, and the server receives the new message, the client sends an update myself message to the client, and if select All is checked The service side will then send a new message broadcast, otherwise traverse all recipients and send the new message to those recipients in turn.

(4) The client disconnects and triggers the service-side disconnect event, and the server sends the leave chat broadcast.

(5) The client updates the chat content in the chat room when it receives the new message update myself. When you receive login success, enter chat, leave chat, the current online user is updated. Update online status When you receive login success, Login failed ...

The code is not much very simple, we can understand it at a glance.

Code address: https://github.com/lesliebeijing/MyChatRoom.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.