Nodejs+websocket Enable chat room functionality

Source: Internet
Author: User

Recently a friend in the project need to implement real-time chat and other features, help to get a rough, on the code.

Server-side

Install Express and Socket.io

NPM Install--save Express

NPM Install--save Socket.io

varApp = require (' Express ')();varHTTP = require (' http '). Server (app);varIO = require (' Socket.io ') (HTTP); App.get (‘/‘,function(req, res) {Res.send (' );}); Io.on ("Connection",function(socket) {Console.log ("A user Connected"); Socket.on ("Disconnect",function() {Console.log ("A User disconnect"); Io.emit ("Dis", {user_id:socket.name});    }); Socket.on ("Join",function(data) {varUserID =Data.userid; Socket.name=userid; Io.emit ("Joinok", {msg:"Join OK", Userid:userid});    }); Socket.on ("Xiaoxi",function(data) {Io.emit ("Message", data); });}); Http.listen (1000,function() {Console.log (' Listening on *:1000 ');});

Client

Introduction of Socket.io

     //connecting to a server    varSocket =Io.connect (Server_add); Socket.emit ("Join", {userid:user_id}); Socket.on ("Joinok",function(data) {Rtop.append (' <p> ' +data.userid+ ' join the chat room </p> ');    }); functionSENDFN () {varval =$.trim (Text.val ()); if(val = = "")returnAlert ("Please enter"); Socket.emit ("Xiaoxi", {user_id:user_id, msg:val}); } socket.on ("Message",function(data) {Rtop.append (' <p> ' +data.user_id+ ' said: ' +data.msg+ ' </p> '); if(data.user_id = = user_id) text.val ("");    }); Socket.on ("Dis",function(data) {Rtop.append (' <p> ' +data.user_id+ ' leave </p> '); });

Nodejs+websocket to implement chat room functionality

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.