Build a simple Chat program using node. JS and Socket.io
Create a folder under the node. JS root Chat, add two files inside: App.js and index.html
App.js
varFS = require ('FS'), HTTP= Require ('http'), Socketio= Require ('Socket.io'); varServer =Http.createserver (function (req, res) {Res.writehead ( $, {'Content-type':'text/html'}); Res.end (Fs.readfilesync (__dirname+'/index.html'));}). Listen (8080, function () {Console.log ('Listening at:http://localhost:8080');}); Socketio.listen (server). On ('Connection', function (socket) {Socket.on ('message', Function (msg) {Console.log ('Message Received:', MSG); Socket.broadcast.emit ('message', MSG); });});
Index.html
"Http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script>$ (function () {varIosocket =Io.connect (); Iosocket.on ('Connect', Function () {$ ('#incomingChatMessages'). Append ($ ('<li>Connected</li>')); Iosocket.on ('message', function (message) {$ ('#incomingChatMessages'). Append ($ ('<li></li>'). Text (message)); }); Iosocket.on ('Disconnect', Function () {$ ('#incomingChatMessages'). Append ('<li>Disconnected</li>'); }); }); $('#outgoingChatMessage'). KeyPress (Function (Event) { if(Event. which = = -) { Event. Preventdefault (); Iosocket.send ($ ('#outgoingChatMessage'). Val ()); $('#incomingChatMessages'). Append ($ ('<li></li>'). Text ($ ('#outgoingChatMessage'). Val ())); $('#outgoingChatMessage'). Val ("'); } }); }); </script>Incoming Chat: <ul id="incomingchatmessages"></UL><BR/><input type="text"Id="Outgoingchatmessage"></body>Turn on the server
Node Chat/app.js
Open two chrome input localhost:8080
Transferred from: http://www.cnblogs.com/wancy86/archive/2013/04/28/socket-io_chat.html