Node. js + socket. io online chat room

Source: Internet
Author: User
Tags emit getcolor

Node. js + socket. io online chat room

Node. js + socket. io enables online chat rooms. Follow the instructions in this tutorial and make a slight change.

Node. js: 0.10.31

Express: 3 .*

Create Project chat:


Add several files. The project structure is 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:

// Introduce the package var express = require ('express '), path = require ('path'), app = express (), server = require ('http '). createServer (app), io = require ('socket. io '). listen (server); // set the Log Level io. set ('Log level', 1); // WebSocket connection listens for io. on ('connection', function (socket) {socket. emit ('open'); // notifies the client that the client has been connected // print the handshake information // console. log (socket. handshake); // construct the client object var client = {socket: socket, name: false, color: getColor ()} // Listen to socket for message events. on ('message', function (msg) {var obj = {time: getTime (), color: client. color}; // determine whether the connection is the first time. Use the first message as the username if (! Client. name) {client. name = msg; obj ['text'] = client. name; obj ['author'] = 'system'; obj ['type'] = 'Welcome '; console. log (client. name + 'login'); // return the welcome socket. emit ('system', obj); // broadcast that a new user has logged on to socket. broadcast. emit ('system', obj);} else {// if it is not the first connection, the normal chat message obj ['text'] = msg; obj ['author'] = client. name; obj ['type'] = 'message'; console. log (client. name + 'say: '+ msg); // return the message (which can be omitted) socket. emit ('message', obj); // broadcast messages to other users socket. broadcast. emit ('message', obj) ;}}); // listens for the exit event socket. on ('disconnect', function () {var obj = {time: getTime (), color: client. color, author: 'system', text: client. name, type: 'disconnect'}; // The broadcast user has exited the 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 ('view', _ dirname + '/view'); 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 () ;}); // specifies the html file app of the webscoket client. 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', 'blueiot', 'Brown ', 'burlywood', 'cadetblue']; return colors [Math. round (Math. random () * 10000% colors. length)];}
Chat.html:

 Socket.io - Simple chat
 <script src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script>  <script src="/socket.io/socket.io.js"></script><script src="javascripts/chat.js"></script>Socket.io - Simple chat roomConnecting...
Chat. js:

$ (Function () {var content = $ ('# content'); var status = $ (' # status'); var input = $ ('# input '); var myName = false; // establish a websocket connection. You can use localhostsocket = io for local testing. connect ('HTTP: // 192.168.37.151: 808080'); // confirm the socket after receiving the connection from the server. on ('open', function () {status. text ('Choose a name: ') ;}); // listens to system events, judges welcome or disconnect, and prints system message information socket. on ('system', function (json) {var p = ''; if (json. type = 'Welcome ') {if (myName = json. text) status. text (myName + ': '0000.css ('color', json. color); p ='

System @ '+ json. time +': Welcome '+ json. text +'

';} Else if (json. type = 'disconnect') {p ='

System @ '+ json. time +': Bye '+ json. text +'

';} Content. prepend (p) ;}); // listens to message events and prints the message information socket. on ('message', function (json) {var p ='

'+ Json. author +' @ '+ json. time +': '+ json. text +'

'; Content. prepend (p) ;}); // press enter to submit the chat information input. keydown (function (e) {if (e. keyCode = 13) {var msg = $ (this ). val (); if (! Msg) return; socket. send (msg); $ (this ). val (''); if (myName = false) {myName = msg ;}}});});
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, which is used for testing on the Intranet)

Enter the name, dss, and press Enter:


In computer 2, access the same address, name input, dss2, and press ENTER


This is on Computer 1:

Let's talk a few words:

Computer 2 after the page is closed computer 1:





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.