Node.js 提供了高效率的伺服器端執行環境,但瀏覽器端對 HTML5 的支援程度參差不齊。為了同時做到「相容所有瀏覽器」、「提供優異的即時使用者體驗」,並且讓程式設計師在客戶端與伺服器端寫出一致的程式碼,socket.io 應運而生。
socket.io 的設計目標是支援任何瀏覽器與任何行動裝置。它涵蓋主流 PC 瀏覽器(IE、Safari、Chrome、Firefox、Opera 等)與行動瀏覽器(iPhone Safari、iPad Safari、Android WebKit、WebOS WebKit 等)。
技術上,socket.io 建構在 Node.js 之上,把 WebSocket API 做了簡化並統一了各家通訊介面,底層會自動在 WebSocket、Flash Socket、AJAX long-polling、AJAX multipart streaming、Forever IFrame、JSONP polling 之間選擇可用方案。
一句話總結:socket.io 解決了即時雙向通訊的問題,並統一了伺服器端與客戶端的開發方式。啟動 socket 之後,就像在兩端之間接上了一條管道,彼此都能主動推送訊息。
在命令列執行即可:
npm install socket.io
寫法與一般 HTTP 伺服器沒有兩樣:啟動伺服器、提供服務、處理事件。以下是一個可直接運行的 server.js:
var http = require('http') , url = require('url') , fs = require('fs') , server; server = http.createServer(function(req, res){ // your normal server code var path = url.parse(req.url).pathname; switch (path){ case '/': res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<h1>Hello! Try the <a href="/index.html">Socket.io Test</a></h1>'); res.end(); break; case '/index.html': fs.readFile(__dirname + path, function(err, data){ if (err) return send404(res); res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'}) res.write(data, 'utf8'); res.end(); }); break; default: send404(res); } }), send404 = function(res){ res.writeHead(404); res.write('404'); res.end(); }; server.listen(8080); var io = require('socket.io').listen(server); io.sockets.on('connection', function(socket){ console.log("Connection " + socket.id + " accepted."); socket.on('message', function(message){ console.log("Received message: " + message + " - from client " + socket.id); }); socket.on('disconnect', function(){ console.log("Connection " + socket.id + " terminated."); }); });
客戶端的概念相同:連線到伺服器,然後收發訊息。對應的 index.html 如下:
<!doctype html> <html> <head> <title>Socket.io Test</title> <script src="/json.js"></script> <!-- for ie --> <script src="/socket.io/socket.io.js"></script> </head> <body> <script> var socket; var firstconnect = true; function connect() { if(firstconnect) { socket = io.connect(null); socket.on('message', function(data){ message(data); }); socket.on('connect', function(){ status_update("Connected to Server"); }); socket.on('disconnect', function(){ status_update("Disconnected from Server"); }); socket.on('reconnect', function(){ status_update("Reconnected to Server"); }); socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in " + nextRetry + " seconds"); }); socket.on('reconnect_failed', function(){ message("Reconnect Failed"); }); firstconnect = false; } else { socket.socket.reconnect(); } } function disconnect() { socket.disconnect(); } function message(data) { document.getElementById('message').innerHTML = "Server says: " + data; } function status_update(txt){ document.getElementById('status').innerHTML = txt; } function esc(msg){ return msg.replace(/</g, '<').replace(/>/g, '>'); } function send() { socket.send("Hello Server!"); }; </script> <h1>Socket.io Test</h1> <div><p id="status">Waiting for input</p></div> <div><p id="message"></p></div> <button id="connect" onClick='connect()'/>Connect</button> <button id="disconnect" onClick='disconnect()'>Disconnect</button> <button id="send" onClick='send()'/>Send Message</button> </body> </html>
1. 啟動與載入腳本。伺服器仍交給 Node:開啟命令列視窗,切換到 server.js 所在目錄,執行 node server.js。客戶端這行 <script src="/socket.io/socket.io.js"></script> 是走本地伺服器提供的腳本;若不想依賴本地,也可以直接用公開 CDN:
<script src="https://cdn.socket.io/stable/socket.io.js"></script>
另外要留意 socket = io.connect(null) 這行,此處的 null 代表連線到本地伺服器,改成 "localhost" 效果相同。
2. 讓 socket.io 直接啟動 HTTP 服務。
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { io.sockets.emit('this', { will: 'be received by everyone'}); });
3. 最簡的收發寫法。用 send 發送、用 message 事件接收:
//server.js var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('message', function () { }); }); //index.html <script> var socket = io.connect('https://localhost/'); socket.on('connect', function () { socket.send('hi'); socket.on('message', function (msg) { // my msg }); }); </script>
4. 自訂事件的收發。兩端可以互發事件與資料。發送用 socket.emit(action, data, callback),其中 action 是事件名稱、data 是資料、callback 是回呼函式;接收用 socket.on(action, function),若 emit 時帶了 data,該函式的參數即為這份資料。除了 connect、disconnect、message 這些內建事件,socket.io 也允許自訂事件名稱:
//服務端: io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
//客戶端: <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('https://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
由此可見,send 與 emit 都能用來送資料,差別在於 emit 讓自訂事件的處理更清晰、更有結構。
5. 在伺服器端保存連線相關資料。用 socket 的 get/set 即可:
//服務端 var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('set nickname', function (name) { socket.set('nickname', name, function () { socket.emit('ready'); }); }); socket.on('msg', function () { socket.get('nickname', function (err, name) { console.log('Chat message by ', name); }); }); });
//客戶端 <script> var socket = io.connect('https://localhost'); socket.on('connect', function () { socket.emit('set nickname', confirm('What is your nickname?')); socket.on('ready', function () { console.log('Connected !'); socket.emit('msg', confirm('What is your message?')); }); }); </script>
6. 廣播訊息。例如聊天室中,把訊息送給除了目前這條連線以外的所有人:
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.broadcast.emit('user connected'); });
7. 用 namespace 切分通道。官方稱之為「多個 namespace」,讓同一條連線上可以有多個互相獨立的邏輯通道,而不必建立多次連線:
var io = require('socket.io').listen(80); //Server var chat = io .of('/chat') .on('connection', function (socket) { socket.emit('a message', { that: 'only' , '/chat': 'will get' }); chat.emit('a message', { everyone: 'in' , '/chat': 'will get' }); }); var news = io .of('/news') .on('connection', function (socket) { socket.emit('item', { news: 'item' }); }); //Client <script> var chat = io.connect('https://localhost/chat') , news = io.connect('https://localhost/news'); chat.on('connect', function () { chat.emit('hi!'); }); news.on('news', function () { news.emit('woot'); }); </script>
設定方式很直覺,用過 Express 的人會覺得似曾相識。先看一個小例子:
var io = require('socket.io').listen(80); io.configure('production', function(){ io.enable('browser client etag'); io.set('log level', 1); io.set('transports', [ 'websocket' , 'flashsocket' , 'htmlfile' , 'xhr-polling' , 'jsonp-polling' ]); }); io.configure('development', function(){ io.set('transports', ['websocket']); });
重點整理:
configure 用來區分不同執行環境的行為。第一個參數是環境名稱(常見如 production、development,實際上可為任意字串),第二個參數是進行設定的函式。若省略第一個參數,則該段設定對所有環境都生效。
切換環境靠命令列中的 NODE_ENV 環境變數決定。
set / enable / disable 在 configure 的函式中用來設定各項選項。
可設定的項目清單可參考專案 Wiki:https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
socket.io 簡介:https://davidchambersdesign.com/getting-started-with-socket.io/
官網與安裝使用說明:https://socket.io/
socket.io Wiki:https://github.com/LearnBoost/Socket.IO/wiki
補充一點現況:本文寫於 socket.io 0.9 世代,文中的 io.listen()、io.configure()、socket.set/get 等 API 在 1.x 之後已有變動(例如改用 require('socket.io')(server)、socket.handshake 等),實際開發時請以所用版本的官方文件為準。