Socket.io Online chat Room
The Nodejs series of articles from scratch will introduce how JavaScript can be done as a server-side script through the NODEJS Framework web development. The NODEJS framework is a V8 based engine and is the fastest JavaScript engine at the moment. The Chrome browser is based on V8, and it's fluent to open 20-30 pages. The NODEJS standard Web development framework, express, can help us quickly build a Web site that is more efficient than PHP development and has a lower learning curve. Very suitable for small sites, personalized sites, our own geek site.
About author Dan (Conan), programmer Java,r,php,javascript Weibo: @Conan_Z blog:http://blog.fens.me email:bsspirit@gmail.com
Reprint please indicate the source:
http://blog.fens.me/nodejs-socketio-chat/
Objective
Network chat room in the era of web1.0, but the technical support is relatively limited, mostly through the browser plug-in Bho,javaapplet,flash implementation. Now HTML5 technology surging, through the WebSocket network chat room, is defined as WebSocket's first experiment, like Hello World as simple.
Today, I also finished the experiment, it feels really cool.
Directory Socket.io Introduction Server-side and client-side communication design server implementation of the client implementation of the complete case code 1. Socket.io Introduction
Socket.io is a software package that supports WebSocket protocols for communication at all times, based on the Nodejs architecture. Socket.io provides a complete package for building real-time applications across browsers, and Socket.io is fully implemented by JavaScript.
Based on NODEJS implementation Webscoket other frameworks, please: Nodejs realize websocket 4 ways 2. Server-side and client communication design
The CLIENT1 and server describe the communication process in the figure above, Client2 describes the message communication via broadcast to other clients. CLIENT1 to server initiating a connection request server accept client's connection CLIENT1 Enter login Username server return to welcome server by broadcast to other online users, CLIENT1 has landed client1 send chat information Server return chat information (can be omitted) server through the broadcast to tell other online users, client1 chat message client1 shut down the connection, quit landing server through the broadcast to tell other online users, Client1 has quit
Let's take a look at the test screenshot:
Left: AAA Landing right: BBB landed on the left: Triple A received BBB landing welcome message AAA and BBB Realization dialog right: BBB refresh Browse Auto exit Left: AAA received BBB's exit message right: CCC Landing left: AAA received CCC Login Land Welcome message AAA and CCC to achieve dialogue 3. Server-side implementation
Here we use the Socket.io and EXPRESS3 blending modes to allow both HTTP and WebSocket requests to use port 3000.
Server-side implementation, with only one core file app.js.
Introducing package var Express = require (' Express '), Path = require (' path '), App = Express (), Server = require (' http '). Crea
Teserver (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 (Soc
Ket.handshake); Constructs the client object var client = {Socket:socket, name:false, Color:getcolor ()}//Monitoring of message events Socket.on (' m
Essage ', function (msg) {var obj = {time:gettime (), color:client.color};
The judgment is not the first connection, with the first message as user name if (!client.name) {client.name = msg;
obj[' text ']=client.name;
obj[' author ']= ' System ';
obj[' type ']= ' welcome ';
Console.log (client.name + ' login ');
Returns the Welcome language Socket.emit (' system ', obj);
Broadcast new user has landed Socket.broadcast.emit (' system ', obj);
}else{//If 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 message (can omit) socket.emit (' Messages ', obj);
The broadcast sends messages to other users socket.broadcast.emit (' message ', obj);
}
});
Listen for a 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 WebsCoket the client's HTML file App.get ('/', function (req, res) {res.sendfile (' 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)];
}
4. Client implementation
Here we need to define several files: chat.html, Chat.js, Jquery.min.js, main.css
1). views/chat.html
<! DOCTYPE html>
2). public/javascript/chat.js
$ (function () {var content = $ (' #content '); var status = $ (' #status '); var input = $ (' #input '); var myname = false;
Establish websocket Connection socket = Io.connect (' http://localhost:3000 ');
Receive Server connection confirmation Socket.on (' open ', function () {Status.text (' Choose a name: ';}); Listen for system events, 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 ' + JSO
N.text + ' </p> ';
} content.prepend (P);
}); Listen for the message event, print the information Socket.on (' Messages ', function (JSON) {var p = ' <p><span style= ' color: ' +json.color+ ';
> ' + json.author+ ' </span> @ ' + json.time+ ': ' +json.text+ ' </p> ';
Content.prepend (P);
}); Submit a chat message Input.keydown (function (e) by "enter"{if (E.keycode = =) {var msg = $ (this). Val (), if (!msg) return; Socket.send (msg), $ (this). Val ("); if (myname = = f
Alse) {myname = msg;}}
});
});
3). public/javascript/jquery.min.js
Official download from jquery: http://jquery.com/
4). public/css/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;
}
5. Complete Case Code
The project has been uploaded to Github:https://github.com/bsspirit/chat-websocket
Download, install, start server
git clone https://github.com/bsspirit/chat-websocket.git
npm install
node app.js
Open your browser
You can open a few more windows and simulate conversations with different users.
http://localhost:3000
It feels great to finish the experiment. The revolution of technological innovation.
Reprint please indicate the source:
Http://blog.fens.me/nodejs-socketio-chat/Aug 2013 Tags:chat Javascript nodejs socket.io socketio comments:82 commen TS Socket.io online chat room
The Nodejs series of articles from scratch will introduce how JavaScript can be done as a server-side script through the NODEJS Framework web development. The NODEJS framework is a V8 based engine and is the fastest JavaScript engine at the moment. The Chrome browser is based on V8, and it's fluent to open 20-30 pages. The NODEJS standard Web development framework, express, can help us quickly build a Web site that is more efficient than PHP development and has a lower learning curve. Very suitable for small sites, personalized sites, our own geek site.
About author Dan (Conan), programmer Java,r,php,javascript Weibo: @Conan_Z blog:http://blog.fens.me email:bsspirit@gmail.com
Reprint please indicate the source:
http://blog.fens.me/nodejs-socketio-chat/
Objective
Network chat room in the era of web1.0, but the technical support is relatively limited, mostly through the browser plug-in Bho,javaapplet,flash implementation. Now HTML5 technology surging, through the WebSocket network chat room, is defined as WebSocket's first experiment, like Hello World as simple.
Today, I also finished the experiment, it feels really cool.
Directory Socket.io Introduction Server-side and client-side communication design server implementation of the client implementation of the complete case code 1. Socket.io Introduction
Socket.io is a software package that supports WebSocket protocols for communication at all times, based on the Nodejs architecture. Socket.io provides a complete package for building real-time applications across browsers, and Socket.io is fully implemented by JavaScript.
Based on NODEJS implementation Webscoket other frameworks, please: Nodejs realize websocket 4 ways 2. Server-side and client communication design
The CLIENT1 and server describe the communication process in the figure above, Client2 describes the message communication via broadcast to other clients. CLIENT1 to server initiating a connection request server accept client's connection CLIENT1 Enter login Username server return to welcome server by broadcast to other online users, CLIENT1 has landed client1 send chat information Server return chat information (can be omitted) server through the broadcast to tell other online users, client1 chat message client1 shut down the connection, quit landing server through the broadcast to tell other online users, Client1 has quit
Let's take a look at the test screenshot:
Left: AAA Landing right: BBB landed on the left: Triple A received BBB landing welcome message AAA and BBB Realization dialog right: BBB refresh Browse Auto exit Left: AAA received BBB's exit message right: CCC Landing left: AAA received CCC Login Land Welcome message AAA and CCC to achieve dialogue 3. Server-side implementation
Here we use the Socket.io and EXPRESS3 blending modes to allow both HTTP and WebSocket requests to use port 3000.
Server-side implementation, with only one core file app.js.
Introducing package var Express = require (' Express '), Path = require (' path '), App = Express (), Server = require (' http '). Crea
Teserver (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 (Soc
Ket.handshake); Constructs the client object var client = {Socket:socket, name:false, Color:getcolor ()}//Monitoring of message events Socket.on (' m
Essage ', function (msg) {var obj = {time:gettime (), color:client.color};
The judgment is not the first connection, with the first message as user name if (!client.name) {client.name = msg;
obj[' text ']=client.name;
obj[' author ']= ' System ';
obj[' type ']= ' welcome ';
Console.log (client.name + ' login ');
Returns the Welcome language Socket.emit (' system ', obj);
Broadcast new user has landed Socket.broadcast.emit (' system ', obj);
}else{//If 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 message (can omit) socket.emit (' Messages ', obj);
The broadcast sends messages to other users socket.broadcast.emit (' message ', obj);
}
});
Listen for a 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 WebsCoket the client's HTML file App.get ('/', function (req, res) {res.sendfile (' 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)];
}
4. Client implementation
Here we need to define several files: chat.html, Chat.js, Jquery.min.js, main.css
1). views/chat.html
<! DOCTYPE html>
2). public/javascript/chat.js
$ (function () {var content = $ (' #content '); var status = $ (' #status '); var input = $ (' #input '); var myname = false;
Establish websocket Connection socket = Io.connect (' http://localhost:3000 ');
Receive Server connection confirmation Socket.on (' open ', function () {Status.text (' Choose a name: ';}); Listen for system events, 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 ' + JSO
N.text + ' </p> ';
} content.prepend (P);
}); Listen for the message event, print the information Socket.on (' Messages ', function (JSON) {var p = ' <p><span style= ' color: ' +json.color+ ';
> ' + json.author+ ' </span> @ ' + json.time+ ': ' +json.text+ ' </p> ';
Content.prepend (P);
}); Submit a chat message Input.keydown (function (e) by "enter"{if (E.keycode = =) {var msg = $ (this). Val (), if (!msg) return; Socket.send (msg), $ (this). Val ("); if (myname = = f
Alse) {myname = msg;}}
});
});
3). public/javascript/jquery.min.js
Official download from jquery: http://jquery.com/
4). public/css/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;
}
5. Complete Case Code
The project has been uploaded to Github:https://github.com/bsspirit/chat-websocket
Download, install, start server
git clone https://github.com/bsspirit/chat-websocket.git
npm install
node app.js
Open your browser
You can open a few more windows and simulate conversations with different users.
http://localhost:3000
It feels great to finish the experiment. The revolution of technological innovation.
Reprint Please specify the Source:
http://blog.fens.me/nodejs-socketio-chat/