安裝流程參考 http://www.cnblogs.com/seanlv/archive/2011/11/22/2258716.htmlhtml
<1>Node.js (https://nodejs.org/)node
安裝 一路nextjquery
cmd node -v 顯示版本號即安裝成功git
<2>安裝npmgithub
https://github.com/npm/npm/tags 下載最新版本web
解壓至 D:/npmjsexpress
安裝npm過程, cmdnpm
D:\>cd npmjs
D:\npmjs>node cli.js install -gf
而後將" nodejs的路徑 /node_modules"加入系統環境變量"NODE_PATH"中json
<3>經過npm安裝Expressapp
cmd
npm install express -g //安裝最新版express
<4>socket.io (http://socket.io/get-started/chat/)
新建文件夾 chat-example, 裏面新建 manifest file package.json
//manifest file describes our project { "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {} }
in order to easily populate the dependencies
with the things. cmd->
npm install --save express
npm install --save socket.io
具體代碼
//index.js //Express initializes app to be a function handler that you can supply to an HTTP server var app = require('express')(); var http = require('http').Server(app); //a new instance of socket.io by passing the http (the HTTP server) object var io = require('socket.io')(http); //We define a route handler / that gets called when we hit our website home. app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); //listen on the connection event for incoming sockets io.on('connection', function(socket){ socket.broadcast.emit('hi'); socket.on('chat message', function(msg){ //console.log('message: ' + msg); io.emit('chat message', msg); }); socket.on('disconnect', function(){ //console.log('user disconnected'); io.emit('chat message', 'disconnected'); }); }); //We make the http server listen on port 3000. http.listen(3000, function(){ console.log('listening on *: 3000'); });
//index.html
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off"/><button>Send</button> </form> <!--That’s all it takes to load the socket.io-client, which exposes a io global, and then connect. --> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); //when the user types in a message, the server gets it as a chat message event. $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body> </html>
<5>運行
cmd: cd->chat_example
node index.js