Node.js+socket.io Online chat Room

Source: Internet
Author: User
Tags emit getcolor

Node.js+socket.io implementation of online chat room, according to this tutorial, a little change can be achieved.

node.js:0.10.31

express:3.*

Create a project chat:


Add several files to the project structure as follows

Code:

Package.json:

{  "name": "Application-name",  "version": "0.0.1",  "private": True,  "scripts": {    "start": "Node App.js "  },  " dependencies ": {    " Express ":" 3.16.7 ",    " Ejs ":" * "," Socket.io ":" * "  }}
App.js:

Introduction package var Express = require (' Express '), Path = require (' path '), App = Express (), Server = require (' http '). Createser Ver (APP), Io = require (' Socket.io '). Listen (server);//Set Log level Io.set (' Log levels ', 1); WebSocket Connection Monitor Io.on (' Connection ', function (socket) {socket.emit (' open ');//Notify client connected//Print handshake information//console.log (socket.  handshake);  Constructs client-side objects var client = {Socket:socket, name:false, Color:getcolor ()}//listens to the message event Socket.on (' message ',    Function (msg) {var obj = {time:gettime (), color:client.color};        The judgment is not the first connection, with the first message as the user name if (!client.name) {client.name = msg;        obj[' text ']=client.name;        obj[' author ']= ' System ';        obj[' type ']= ' welcome ';        Console.log (client.name + ' login ');        Back to welcome Socket.emit (' system ', obj);     Broadcast new user has landed Socket.broadcast.emit (' system ', obj);        }else{//If it is not the first time connection, the normal chat message obj[' text ']=msg;              obj[' author ']=client.name;        obj[' type ']= ' message '; Console. log (Client.name + ' say: ' + msg);        Return message (can be omitted) socket.emit (' message ', obj);      Broadcast messages to other users socket.broadcast.emit (' message ', obj);    }    });        Listen for fallback event Socket.on (' Disconnect ', function () {var obj = {time:gettime (), Color:client.color,      Author: ' System ', text:client.name, type: ' Disconnect '};      The broadcast user has exited Socket.broadcast.emit (' system ', obj);    Console.log (client.name + ' Disconnect '); });});/  /express Basic Configuration App.configure (function () {app.set (' Port ', Process.env.PORT | | 3000);  App.set (' views ', __dirname + '/views ');  App.use (Express.favicon ());  App.use (Express.logger (' dev '));  App.use (Express.bodyparser ());  App.use (Express.methodoverride ());  App.use (App.router); App.use (Express.static (Path.join (__dirname, ' public '));}); App.configure (' development ', function () {App.use (Express.errorhandler ());}); /Specify the Webscoket client's HTML file App.get ('/', function (req, res) {res.sendfile (' chat/views/chat.html ');}); Server.listen (App.get (' Port '), function () {Console.log ("Express Server listening on port" + app.get (' Port ');});  var gettime=function () {var date = new Date (); return date.gethours () + ":" +date.getminutes () + ":" +date.getseconds ();}                var getcolor=function () {var colors = [' AliceBlue ', ' antiquewhite ', ' Aqua ', ' aquamarine ', ' pink ', ' red ', ' green ',  ' Orange ', ' Blue ', ' blueviolet ', ' Brown ', ' burlywood ', ' cadetblue '; Return Colors[math.round (Math.random () * 10000% colors.length)];}
Chat.html:

<! DOCTYPE html>
Chat.js:

$ (function () {var content = $ (' #content '), var status = $ (' #status '), var input = $ (' #input '), var myName = false;//established WEBSOC Ket connection, the native test can be used Localhostsocket = Io.connect (' http://192.168.37.151:3000 ');//Receive the server's connection confirmation Socket.on (' open ', function () {Status.text (' Choose a Name: ');}); /Listen to the system event, Judge welcome or disconnect, print systems message information Socket.on (' System ', function (JSON) {var p = '; if (json.type = = = ' Welcome ') { if (myname==json.text) status.text (myName + ': '). CSS (' color ', json.color);p = ' <p style= ' background: ' +json.color+ ' " >system @ ' + json.time+ ': Welcome ' + json.text + ' </p> ';} else if (Json.type = = ' Disconnect ') {p = ' <p style= ' background: ' +json.color+ ' ">system @ ' + json.time+ ': Bye ' + JSON . Text + ' </p> ';} Content.prepend (P);}); /Listen for message event, print messages Information Socket.on (' message ', function (JSON) {var p = ' <p><span style= "color: ' +json.color+ ';" > ' + json.author+ ' </span> @ ' + json.time+ ': ' +json.text+ ' </p> '; content.prepend (P);}); /Submit Chat information via "Enter" Input.keydown (function (e) {if (e.keYcode = = =) {var msg = $ (this). Val (), if (!msg) return;socket.send (msg); $ (this). Val ("); if (MyName = = = False) {myName = m (SG;}});});
MAIN.CSS:

* {padding:0px; margin:0px;} Body{font-family:tahoma; font-size:12px;margin:10px;} p {line-height:18px;padding:2px;} div {width:500px;} #content {     padding:5px;     Background: #ddd;     border-radius:5px;    border:1px solid #CCC;     margin-top:10px; } #input {     border-radius:2px;     border:1px solid #ccc;    margin-top:10px;     padding:5px;     width:380px;  } #status {     width:100px;     Display:block;     Float:left;     margin-top:15px; }
In Computer 1, the browser accesses Http://192.168.37.151:3000/(http://localhost:3000, here is to test in the intranet)

Enter name, DSS, enter:


In Computer 2, access the same address, name input, DSS2, enter


This is on Computer 1:

Let's talk a few words:

PC 2 turn off page after PC 1:





Node.js+socket.io Online chat Room

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.