NodeJS+Express+Socket.io的一個簡單例子

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   for   sp   

關鍵字:NodeJS,Express,Socket.io。

OS:Windows 8.1 with update pro。

 

1.安裝NodeJS:http://nodejs.org/。

 

2.初始化一個NodeJS web應用:

開啟CMD視窗。

運行cmd:“mkdir myapp”,建立一個檔案夾,名為myapp。

運行cmd:“cd myapp”,切換到檔案夾myapp。

運行cmd:“npm init”,建立檔案package.json。

 

3.Express入門應用:

在上面的CMD視窗運行cmd:“npm install express --save”, 安裝“express” node_module, "--save"表示儲存express到package.json。

添加檔案app.js到myapp檔案夾,假設package.json裡面的main是app.js。

//app.jsvar app = require(‘express‘)();var http = require(‘http‘).Server(app);app.get(‘/‘, function(req, res){  res.send(‘<h1>Hello world</h1>‘);});http.listen(3000, function(){  console.log(‘listening on *:3000‘);});

運行cmd:“node app”,啟動myapp。

在Chrome裡開啟“http://localhost:3000/”,顯示“Hello world”。

在CMD視窗裡輸入“Ctrl+C”,可終止myapp的運行。

 

4.Socket.io入門應用

在上面的CMD視窗運行:“npm install --save socket.io”。

添加index.html到myapp檔案夾,內容如下:

<!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>          <script src="/socket.io/socket.io.js"></script>    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>    <script>      var socket = io();      $(‘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>

修改app.js如下:

//app.jsvar app = require(‘express‘)();var http = require(‘http‘).Server(app);var io = require(‘socket.io‘)(http);app.get(‘/‘, function(req, res){  res.sendfile(‘index.html‘);});io.on(‘connection‘, function(socket){  console.log(‘a user connected‘);  socket.on(‘disconnect‘, function(){    console.log(‘user disconnected‘);  });      socket.on(‘chat message‘, function(msg){    console.log(‘message: ‘ + msg);    io.emit(‘chat message‘, msg);  });});app.set(‘port‘, process.env.PORT || 3000);var server = http.listen(app.get(‘port‘), function() {  console.log(‘start at port:‘ + server.address().port);});

再次運行“node index”,用Chrome開啟“http://localhost:3000/”,顯示如下“

 

引用:

NodeJS:http://nodejs.org/

ExpressJS:http://expressjs.com/

Socket.io: http://socket.io/

NodeJS+Express+Socket.io的一個簡單例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.