1, first http://www.nodejs.org/download node. JS in the official website
2. Open command line cmd, enter the Nodejs\node_modules\ directory, enter NPM install Socket.io installation Socket.io module. Don't hurry. Turn off this cmd window, which is useful later
3, build the service-side code Server.js
1 varHTTP = require (' http ');2 varIO = require (' Socket.io ');3 varCisserver = Http.createserver (function(Request, response) {4Response.writehead, {' Content-type ': ' text/html ' });5Response.End (' start! ');6 7}). Listen (8000);8 9 varCcissocket = Io.listen (cisserver);//. Set (' Log ', 1);TenCcissocket.on (' Connection ',function(client) { OneClient.on (' message ',function(data) { AConsole.log (' Client message ', data); -Client.emit (' message '), data); -Client.on (' Disconnect ',function() {console.log (' disconnect ') }) the }) -})
4, switch before NODEJS Command Line window input node server.js turn on listening mode
5. Client code
1 <!DOCTYPE HTML> 2 <HTML> 3 <Head> 4 <Scriptsrc= ' Http://localhost:8000/socket.io/socket.io.js '></Script> 5 </Head> 6 <Body> 7 <Script> 8 varhtml5websockets= {};9 Html5websockets.socketio= {Ten Yoursocket:NULL, One A Initialize:function () { - - HTML5WebSockets.socketio.yoursocket=Io.connect ('http://localhost:8000'); the - HTML5WebSockets.socketio.yoursocket.on ('Connect', function () { - HTML5WebSockets.socketio.log ('You is connected to server<br/>'); - HTML5WebSockets.socketio.yoursocket.send ("currently has a value"); + }); - + HTML5WebSockets.socketio.yoursocket.on ('message', function(data) { A //alert (data); at HTML5WebSockets.socketio.log ('Server Response:' +Data+ '<br/>'); - }); - - HTML5WebSockets.socketio.yoursocket.on ('Disconnect', function () { - HTML5WebSockets.socketio.log ('You is disconnected from server<br/>'); - }); in - Document.queryselector ('#sendMes'). onclick= function () { to HTML5WebSockets.socketio.sendMessageToServer (document.getElementById ("mes"). value); + document.getElementById ("mes"). Value= "'; - }; the * }, $ Sendmessagetoserver:function(data) {Panax Notoginseng HTML5WebSockets.socketio.yoursocket.send (data); - HTML5WebSockets.socketio.log ('Message to Server:' +Data+ '<br/>'); the }, + A log:function(message) { the document.getElementById ("Log"). InnerHTML+=message; + } - } $ </Script> $ - <DivID= ' log '></Div> - <inputtype= ' text 'ID= ' mes '/> the <Buttontype= ' button 'ID= ' Sendmes '>Send</Button> - <BR/> Wuyi <Script> the HTML5WebSockets.socketio.initialize (); - </Script> Wu </Body> - </HTML>
7. Run the HTML file, enter a value, wait for the result returned by the server