A few nights ago, I watched the node. js chat room written by the hacker. As I mentioned earlier, before the holiday, I had to sort out all my recent experiences with node. js. Today is the bird of the 30th ~ Sahuan ~, Finally, I will release this chat room as a reference for you to learn about nodejs. I hope it will be useful to you.
Thanks to Lao lei in the cnodejs group and the friends on Weibo! I wish you a happy long holiday, and I wish you good luck that the train will not be derailed tomorrow. I wish you no longer have a holiday next year, so I feel more deeply ......
Features
Main functions and features of chat rooms:
- Nodejs)
- Express framework, jade Template
- Socket. io performs frontend and backend websocket Communication
- Support session
- Supports @ private message
I don't need to talk about it anymore. Pay attention to the following:
Configure nodejs.exe's windows directory structure
Install express and configure the app. js File
Using socket. io and node. js to build a websocket Application
Using session in Express and Socket. IO
Nodejs chat room
Chat rooms based on express + socket. io
Js Code on the server side of the chat room
// ==================================================================== ===========================/ *** Modules Introduction */var express = require ('express '), sio = require ('socket. io '), fs = require ('fs'), path = require ('path') url = require ('url'), parseCookie = require ('connect '). utils. parseCookie, MemoryStore = require ('connect/middleware/session/memory ');/*** private chat session */var usersWS = {}, // websocketstoreMemory for private chat = new MemoryStore ({rea PInterval: 60000*10 }); // session store // ============================ app configuration ========== ====================================/*** app configuration */var app = module. export = express. createServer (); app. configure (function () {app. use (express. bodyParser (); app. use (express. cookieParser (); app. use (express. session ({secret: 'wyq', store: storeMemory}); app. use (express. methodOverride (); app. use (app. router); // After bodyParser, process postapp. set ('v Iews ', _ dirname +'/views'); app. set ('view engine ', 'jade'); app. use (express. static (_ dirname + '/public');}); // ========================== configure socket. io ========================================//*** configure the socket. io **/var io = sio. listen (app); // sets sessionio. set ('authorization', function (handshakeData, callback) {// obtain the session data handshakeData through the cookie string of the client. cookie = parseCookie (handshakeData. headers. cookie) var connect_sid = handsh AkeData. cookie ['connect. sid ']; if (connect_sid) {storemory. get (connect_sid, function (error, session) {if (error) {// if we cannot grab a session, turn down the connectioncallback (error. message, false);} else {// save the session data and accept the connectionhandshakeData. session = session; callback (null, true) ;}}) ;}else {callback ('nosession ');}}); // ================== URL ======================== ========== =========/ *** Url Processing starts ~ * @ Param {Object} req * @ param {Object} res */app. get ('/', function (req, res) {if (req. session. name & req. session. name! = '') {// You need to determine if you have logged on to res. redirect ('/chat');} else {// read the logon page, requiring logon to var realpath = _ dirname + '/views/' + url.parse('login.html '). pathname; var txt = fs. readFileSync (realpath); res. end (txt) ;}}); app. get ('/chat', function (req, res) {if (req. session. name & req. session. name! = '') {// You need to determine if you have logged on to res. render ('chat ', {name: req. session. name});} else {res. redirect ('/') ;}}) app. post ('/chat', function (req, res) {var name = req. body. nick; if (name & name! = '') {Req. session. name = name; // set sessionres. render ('chat ', {name: name});} else {res. end ('nickname cannot null ');}}); // =============================== socket link listener ====================== =/*** start socket link listening * @ param {Object} socket */io. sockets. on ('connection', function (socket) {var session = socket. handshake. session; // sessionvar name = session. name; usersWS [name] = socket; var refresh_online = function () {var n = []; for (va R I in usersWS) {n. push (I);} io. sockets. emit ('Online list', n); // All broadcast} refresh_online (); socket. broadcast. emit ('System message', '[' + name + '] is back. Please hurry and talk to him ~~ '); // Public Information socket. on ('Public message', function (msg, fn) {socket. broadcast. emit ('Public message', name, msg); fn (true) ;}); // Private @ information socket. on ('private message', function (to, msg, fn) {var target = usersWS [to]; if (target) {fn (true); target. emit ('private message', name + '[private message]', msg);} else {fn (false) socket. emit ('message error', to, msg) ;}}); // dropped, disconnected to process socket. on ('disconnect', function () {delete usersWS [name]; sess Ion = null; socket. broadcast. emit ('System message', '[' + name + '] Left silently... '); Refresh_online () ;}); // ============ app listen start bird ~ =========== App. listen (3000, function () {var addr = app. address (); console. log ('app listening on http://127.0.0.1 : '+ Addr. port );});