Nodejs-based chat room with repeated wheel Creation

Source: Internet
Author: User

First of all, although this post is original, there have been many implementations on the Internet. I just recorded my progress and configured the node. js environment. You can refer to my other blog post to create a node. js service. Now, let's start with the server code, based on nodejs. A simple config. js file. If you cannot understand the explanation in the code, you can read the blog post about simple node. js service creation. If you still do not understand, leave a message to ask. [Javascript] var express = require ('express '), routesConfig = require ('. /routes/config '), http = require ('HTTP'), routes = require ('. /routes/config '); var app = express (), // port number port = 8888; app. configure (function () {// define a private variable to reduce the retrieval consumption of the scope chain (in fact, there is no need to write this, 0.1 billion searches will have performance differences) var _ app = app, _ express = express // set the View File _ app. set ('view', _ dirname + '/view'); // set template engine _ app. set ('view engine', 'ejs'); // static resource management Management _ app. use (express. static (_ dirname + '/'); app. use (express. favicon (); // (this automatic processing is to put the data carried by post into the request. body) _ app. use (_ express. bodyParser (); // use the Request Header for automatic data processing: // (this automatic processing will, some request header information that is not included in the header or directly included in postData is written to the request. method. If the information is in postData, the post. delete the request header information in the body) _ app. use (_ express. methodOverride (); // use debugging? // This is not clear. It seems that the code corresponding to the interface is related to debug _ app. use (_ app. router) ;}); app. get ('/', routesConfig. default); // accept the message var chat = require (". /routes/chat_box/push "); app. get ('/push', chat. push); // Exception Handling app. configure ('development ', function () {app. use (express. errorHandler () ;}); // create the service and specify the port. After that, the initial port number is http. createServer (app ). listen (port, function () {console. log ("Express server listening on port" + port) ;}); in this Code In, the default access such as: http://xxxx.xxxx.xxx/this type of Automatic Execution of routesConfig. default, this I will not elaborate on, anyway, output an html. Then let's look at the message pushing code [javascript] // url module (nodejs) var urllib = require ('url');/* socket module (nodejs) to enable push port Port: 9999, this port number is actually random, as long as the wood is occupied */var io = require ('socket. io '). listen (9999); // simple queue var queue = function () {var self = this; this. list = []; this. add = function (data, cb) {self. list. push (data); cb & cb () ;}; this. get = function () {return self. list. shift () ;};}; // In fact, this user is a shanzhai database (I used to cache data, so I am lazy here.) Var user = {};/* The connection event bound to the event is. After a link appears on the server, the event is executed. In this event, each user with a link exists, I just opened a piece of memory for it to store push information. I didn't optimize it here. If there are many users, I should be very confused and then execute the push data listener */io. sockets. on ('connection', function (socket ){(! User [socket. id]) & (user [socket. id] = new queue (); _ push (socket);});/* enable the push data listener and use setInterval to forge a multi-thread. I have no idea, there is a good solution for communication */var _ push = function (socket) {var _ setInterval; _ setInterval = setInterval (function () {var item = user [socket. id] & user [socket. id]. get (); if (item) {socket. emit ("chat_box", item) ;}}, 100) ;};/* interface for receiving and sending messages. Do you remember the configured js? Var chat = require (". /routes/chat_box/push "); app. get ('/push', chat. push); this statement is forwarded to this interface to process */exports. push = function (req, res) {var params, uname, quantity, text; params = urllib. parse (req. url, true ). query; uname = params. uname; quantity = params. quantity; text = params. text; // After receiving the sent message, add the PUSH message for (var I in user) {user [I] to each linked user. add ({userName: uname, flowersQuantity: quantity, text: text} )} // Server monitoring. You can view the console at the command prompt. log ('new message') ;}; this is the case with the server-side code. The socket is mainly used here. the node. js plug-in I/O. Next, let's take a look at the client script. It should be noted that the requirements are different at the beginning of the writing, and the individual names are still the initial names. From an English perspective, it is a bit awkward. [Javascript] // simple queue var queue = function () {var self = this; this. list = []; this. add = function (data, cb) {self. list. push (data); cb & cb () ;}; this. get = function () {return self. list. shift () ;}}// receiving queue var flowersQueue = new queue () // singletonMsgQueue () // package queue, boxMsgQueue = new queue () // The total number of flowers sent by the user is saved to the object, userData ={}, $ chat_box =$ ("# chat_box");/* Implementation logic: 1. New data appears 2. Data enters Receiving queue 3. Execute the callback to the receiving Queue (determine whether the sending data is a singleton or a package, and define the package as the data to be flushed) 4. Singleton data, that is, data that does not need to be flushed is directly sent to the singleton queue. 5. Package data is split into Singleton data to enter Singleton queue. 6. Listeners are used to listen to singleton queues, output the callback after the new data is sent to the queue according to the step size * // (internal judgment, single-case data delivery or data delivery package) var flowersQueueAddCallBack = function () {// obtain a data var _ item = flowersQueue from the queue. get (); // returns if it does not exist... You know if (! _ Item) return; // if a property value in the data needs to be flushed, I wrote if (_ item. flowersQuantity = 20) {// enter the package queue and execute the callback boxMsgQueue. add (_ item, function () {boxMsgQueueAddCallBack () ;});} else {/* also has business logic, that is, sending common chat information and sending flowers, this is the way to directly enter the single-instance queue. In fact, this process will be caused by the speed of the network, the machine is good or bad, resulting in chat, and cannot be synchronized with all users when the screen is flushed. In fact, we can directly append the container, obtain the data in a single instance, and insert the data directly. I haven't modified this for the time being, in the next version, I want to optimize it */if (_ item. flowersQuantity! = 0) {userData [_ item. userName] = (userData [_ item. userName] | 0) + (_ item. flowersQuantity-0); singletonMsgQueue. add ('<p>' + _ item. userName + 'complimentary '+ _ item. flowersQuantity + 'Flowers, total '+ userData [_ item. userName] + 'Multiple </p> ');} else {singletonMsgQueue. add ('<p>' + _ item. userName + ":" + _ item. text + '</p>') ;}}; // Add new package data into, callback after the package data queue (new package data appears, according to The step size, split into Singleton data into Singleton queues) var boxMsgQueueAddCallBack = function () {// Value, same as var _ item = boxMsgQueue. get (); var I, _ setInterval; if (! _ Item) return // insert a single-instance queue by step I = 0; _ setInterval = setInterval (function () {I ++; userData [_ item. userName] = (userData [_ item. userName] | 0) + 1; singletonMsgQueue. add ('<p>' + _ item. userName + 'present a flower, total '+ userData [_ item. userName] + 'Multiple </p> '); if (I = _ item. flowersQuantity) {clearInterval (_ setInterval) ;}, 200) ;}; // listen to the singleton queue and insert text (whether it is Singleton data or package data, all processed data enters the singleton queue.) var monitorSingletonMsgQueue = function () {// obtain the first var _ item = singletonMsgQueue in the queue. get (); var I; // data in the queue if (_ item) {// Insert a new data $ chat_box.append (_ item ). scrollTop (10000); ($ chat_box.find ("p "). length> 200) & ($ chat_box.find ("p: eq (0 )"). remove (); // if (singletonMsgQueue. list. length> 100) {I = singletonMsgQueue. list. length; while (I --) {$ chat_box.append (singletonMsgQueue. get ()). scrollTop (10000); ($ chat_box.find ("p "). length> 200) & ($ chat_box.find ("p: eq (0 )"). remove () ;}}}// listener setInterval (function () {monitorSingletonMsgQueue () ;}, 200); // get push information var socket = io. connect ('HTTP: // 10.0.252.124: 808080'); // This is the recursion of the push information. You only need to put the pushed data into the queue, and you can use socket. on ('chat _ box', function (data) {flowersQueue. add (data, function () {flowersQueueAddCallBack ();});});

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.