DIV CSS 佈局教程網

基於 socket.io 與 Node.js 搭建即時通信系統
編輯:關於JavaScript     

socket.io 不僅能搭建客戶端的 WebSocket 服務,也支援 Node.js 伺服器端的 WebSocket。以下就來介紹如何在 Node.js 環境中安裝配置並實作一個即時通信的範例。

安裝與配置 Node.js

可前往 Node.js 官網下載 msi 安裝檔,一路點擊 next 完成安裝,檔案會自動裝到 C:\nodejs 目錄下。安裝完成後通常會自動配置環境變數;若沒有,可手動在 path 加上 ;C:\nodejs\。

接著需要配置 npm 來管理 Node.js 的模組。在 Windows 下安裝 npm 需要先安裝 git,安裝好 git 後打開 git bash,執行以下步驟:

git config --system http.sslcainfo /bin/curl-ca-bundle.crt
git clone --recursive git://github.com/isaacs/npm.git
cd npm
node cli.js install npm -gf

其中第一個命令設定不會有任何提示,第二個會從 GitHub 下載 npm 並顯示進度,最後一個則把 npm 安裝到 Node.js(會複製 cmd 檔與 node_modules 資料夾到 nodejs 目錄)。如此一來 npm 便配置完成,之後要安裝任何模組,直接輸入 npm install 加模組名稱即可。

安裝 socket.io

使用 npm 這個套件管理工具,執行以下命令即可安裝 socket.io:

npm install socket.io

客戶端範例

以下是一個客戶端的實作,按下按鈕後連線到伺服器,並示範雙向資料傳輸:

<html>
<head>
<title></title>
<script src="../js/socket.io.client.js"></script>
<script type="text/javascript">
function doit() {
  var socket = io.connect('https://localhost');
  socket.on('news', function (data) {
    // 接收到伺服器發送過來、名為 news 的資料
    console.log(data.hello);
    // 向伺服器發送資料,實現雙向資料傳輸
    socket.emit('my new event', { my: 'new data' });
  });
  socket.on('other', function (data) {
    // 接收另一個名為 other 的資料
    console.log(data.hello);
    socket.emit('event1', { my: 'other data' });
  });
}
</script>
</head>
<body>
<button id='btn' onclick="doit()">click me</button>
</body>
</html>

socket.io.client.js 可從官方 GitHub 下載到本地,並在 <script src=".."> 中指向本機的 js 函式庫。

伺服器端範例

伺服器以 Node.js 實作,檔名為 server2.js:

var http = require('http'),
  io = require('socket.io'),
  express = require('express');

var app = express.createServer(),
  io = io.listen(app);
app.listen(80);

io.sockets.on('connection', function (socket) {
  // 一旦客戶端連上,即發送名為 news 的資料
  socket.emit('news', { hello: 'world' });
  // 捕獲客戶端發送、名為 my other event 的資料
  socket.on('my other event', function (data) {
    console.log(data.my);
  });
  // 發送另一個名為 other 的資料
  socket.emit('other', { hello: 'other world' });
  socket.on('event1', function (data) {
    console.log(data.my);
  });
});

測試結果顯示,客戶端能正常顯示伺服器推送的訊息,伺服器端也能收到客戶端回傳的資料,雙向通訊成功。要特別注意的是,程式碼必須和 node_modules 放在同一個目錄下,否則會出現找不到 socket.io 模組的錯誤。透過 socket.io 的事件機制,我們能輕鬆建立即時、雙向的即時通信系統。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved