Nodejs implementation of chat rooms based on Socket.io

Source: Internet
Author: User
Tags emit md5 encryption sendfile

As a result of the Web-based video live project to use the Socket.io module, so take time to study the next, referring to the online code to do some improvement, I wrote a chat room code. I have to admit that the back-end fact push ability is a bit bad, this is what I used to use PHP has been plagued by things. The following is a brief introduction to my project, incidentally, the next Nodejs.

In fact, I never knew what Nodejs was doing until I saw the code written by someone else, until I realized that it could be counted as a service-side code, and the rich third-party library made it extremely powerful. It can open the server directly from the command line like Golang's Beego, but uses the Express module. The modules are loaded in a way similar to PHP, as follows:

var express = require (' Express '); Quote Express
The following lines of code are required to open a server:

var express = require (' Express '); Reference Expressvar app = Express (); var server = require (' http '). Server (APP);//Listener Server Boot Server.listen ((), function () {Console.log ("Express Server listening on port" + app.get (' Port ') ;});
Use Console.log to print messages at the command line after the server has been successfully opened and convenient.

The next step is to define the route, in fact Nodejs has a routing module, but I have not studied the module specifically implemented what functions, only borrow someone else's code to write basic routes, the approximate form is as follows:

App.set (' views ', __dirname + '/views '); App.get ("/", Function (req, res) {//res.send (' Hello World '); Res.sendfile ( App.get ("views") + '/login.html ');//res.redirect ('/login ');});

Req is the request, RES response returns, which is somewhat similar to javaweb. Res.send is probably the direct output string content to the page, while Sendfile is the content of the specified file output to the page, redirect is redirected. If I turn on the server on port 3000, the above code specifies that when I access localhost:3000/through the Get method, the contents of the views/login.html are output to the page, which is actually the views/login.html page. Get is the Get method in App.get. Similarly, to write the interface for a POST request, use App.post.Note: This App object is the Express object that the article begins to define.

Describe the route and then introduce the template. Since Nodejs can be developed as a service-side language, template modules are naturally indispensable. Of course, Nodejs has a lot of template modules, this way I only understand the Ejs module, just introduce this.

The method is called as follows:

App.set ("View Engine", "Ejs");//chat Room home app.get ('/index ', function (req, res) {Res.render ("index", {"User": Req.session.user});
Call the Res.render method to pass the value to the page, the first parameter that is the name of the template page is Views/index.ejs (note suffix is ejs), the second parameter is the accompanying data, since it is JS, the accompanying data is naturally JS JSON data.Note: In Nodejs, views and view seem to have provisions, define the page path when App.set (' views ', __dirname + '/views '), the program runs successfully, and App.set (' view ', __dirname + '/ Views '), will be error, the wrong reason forget, anyway, I looked at the English forum under the reply to know is this problem, define the page path is best to use views it。

In the template page call is also very convenient, direct <%=user%> can. As follows:

<input type= "hidden" value= "<%=user%>" id= "user"/>
Req.session.user I used the session module. Because my chat room did the landing page, by the way the next session module familiar with familiar. The method is called as follows:

var session = require (' express-session '); If you want to use the session, you need to include this module App.use ({secret: ' Scumvirus ', Name: ' Sv_chat ',//The name here is worth the name of the cookie, The default cookie name is: Connect.sidcookie: {maxage:3600000},//Set MAXAGE is 3600000ms, that is 1h after session and corresponding cookie expiration resave:false, Saveuninitialized:true,}));//Set sessionreq.session.user = "Scumvirus";//Get Sessionvar name = Req.session.user;
Nodejs also provides the encryption module, can be very convenient to encrypt the string, I generally use 32-bit MD5 encryption, only to get 32-bit MD5 encryption method, as follows:

var crypto = require (' crypto '); Encrypt//Get MD5 value after encryption var getMD5 = function (str) {var MD5 = Crypto.createhash (' MD5 '); md5.update (str); var d = md5.digest (' hex ') ; return D;}

In addition I used the MySQL module, used to connect MySQL database, to achieve the foreground registration login, called as follows:

var MySQL = require ("MySQL");//Database module//connection database var Connpool = Mysql.createpool ({host : ' 127.0.0.1 ',//Host User: ' Root ',//mysql authenticated user name password: ' admin ',//mysql authenticated user password port: ' 3306 ',//Port number database: ' Sv_chat ',// Database waitforconnections:true,//When the connection pool is not connected or exceeds the maximum limit, set to true and the connection is placed in the queue//connectionlimit:10,//connection limit});//user information var based on users Getuserbyid = function (name, callback) {//Execute SQL statement var sql = ' select * from Sv_user where name=? '; var params = [Name];connpool.query (sql, params, function (err, result) {if (err) {Console.log (' [SELECT ERROR]-', err.mess (age); return;} Return callback (Result[0]);} Add New user var addUser = function (params, callback) {//Execute SQL statement var sql = ' INSERT into Sv_user (' name ', ' pwd ', ' email ', ' phone ', ' Create_time ') VALUES (?,?,?,?,?) '; Connpool.query (SQL, params, function (err, result) {if (err) {Console.log (' [INSERT ERROR]-', err.message); return Callbac K (false);} else {console.log (' INSERT ID: ', Result.insertid); return callback (TRUE);}});} 
If you're interested, you can print the results of the query yourself. Result is JSON-formatted data, with Insetid, and affectedrows, almost the same as PHP. But the only thing about the pit daddy is that the query database executes asynchronously, and to return the results of the query to the foreground page, the possible values are not always available, and the callback method must be used wisely. There is also an introduction on the Internet that can be executed linearly, but I have not studied it carefully, the callback I understand quickly, then the callback function is processed first.

Finally is the most critical communication phase, Socket.io module, the background code is as follows:

var io = require (' Socket.io '). Listen (server); Socket IO module//websocket connection monitor io.on (' Connection ', function (socket) {//socket.emit (' open ', onlinemember);//Notification client is connected// Print handshake information//Console.log (Socket.handshake);//Construct client object var client = {name: ',}//listener//Login Event Socket.on (' login ') for message Event function (name) {var time = GetTime (); client.name = Name;var index = getarrindex (Name,onlinemember); if (index = =-1) {Online Member.push (Client.name); Console.log (Time + "" + client.name + "login"); var obj = {time:time,author:client.name,text: ', type: ' Login ', member:onlinemember};socket.emit (' system ', obj); Socket.broadcast.emit (' system ', obj);}); /Message Event Socket.on (' Message ', function (msg) {var obj = {time:gettime (),};obj[' msg '] = msg;obj[' author '] = client.name;obj[' Type '] = ' message ';//return message (can be omitted) socket.emit (' message ', obj);//broadcast message to other user socket.broadcast.emit (' message ', obj);}); /Listener Exit Event Socket.on (' Disconnect ', function () {var index = Getarrindex (Client.name, Onlinemember); if (Index >-1) { Onlinemember.splice (Index, 1);} var time = GetTime (), var obj = {time:time,author:client.name,text: ', type: ' Loginout ', Member:onlinemember};console.lo G (Time + "" + Client.name + "loginout");//broadcast user has exited Socket.broadcast.emit (' system ', obj);});
Front-Desk Connection code:

<script src= "/socket.io/socket.io.js" ></script><script>//establish websocket connection socket = Io.connect (' http ://localhost:3000 '); var userName = $ ("#user"). Val (); Socket.emit (' login ', userName);</script>
Socket.emit can be understood as a method of bidirectional communication, if client A is connected to Server B, then a calls the emit method, then B receives the message, B calls the emit method, and a receives the message. The Socket.broadcast.emit method is broadcast, if the client a,b,c simultaneously connected to the server d,a through emit send a message to D,d to receive the message after the broadcast method, then B,c received the message, and a will not receive the message. Login is my custom push message type, message is the type defined by the plug-in itself, the foreground can be triggered by Socket.send (msg), and disconnect is also the type defined by the plug-in, which is called when the client disconnects.

Finally put on my source code: Nodejs Chat Room






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Nodejs implementation of chat rooms based on Socket.io

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.