這是Node.js最常用到的套件,Socket.io的優點就是可以達到Server push的效果,且其中連線是使用handshake,如果要做一些與使用即時互動的功能,使用socket.io是最適合不過的(socket.io source)

安裝

npm install socket.io

使用範例
Server side

//Express 3.x
var express = require('express');
var app = express();
var server = require('http').createServer(app)
var io = require('socket.io').listen(server);

//listen port
server.listen(1234);

//.on()為socket的接收端,預設的key值是connection
io.sockets.on('connection', function (socket) {
    //接收key值為set nickname的socket,並傳入一個變數name
    socket.on('set nickname', function (name) {
        //.set()為設定socket中的暫存變數,當同個變數內容使用範圍不止在這個區域時可以使用,可同時帶入function執行動作
        socket.set('nickname', name, function () {
            //.emit()為socket的發送端
            socket.emit('ready', name);
        });
        //.get()為取得socket中暫存的變數
        socket.get('nickname', function(error, name) {
            console.log(name);
        });
    });
});

Client side

<script src="//IP:1234/socket.io/socket.io.js"></script>
//連接伺服器端的socket.io
var socket = io.connect('http://120.119.29.125:1234');
//.on()為socket的接收端,client端預設的key值是connect
socket.on('connect', function () {
	//.emit()為socket的發送端
	socket.emit('set nickname', prompt('你的名字?'));
	
	//.on()為socket的接收端
	socket.on('ready', function ( name ) {
		//do something
	});
});

Server Broadcast(發送給其他在線上的socket)

//將emit()改成broadcast.emit()即可 (注意,該broadcast自己會收不到)
socket.broadcast.emit('user connected','test');

//broadcast全部,包括自己
io.sockets.emit('user connected','test');

Authorization
socket.io也可以從 handshake Object 取得一些連線資料 (參考文件)

io.sockets.on('connection', function (socket) {
    console.log(socket.handshake);
});

handshake Object 格式

{
   headers: req.headers       // <Object> the headers of the request
 , time: (new Date) +''       // <String> date time of the connection
 , address: socket.address()  // <Object> remoteAddress and remotePort object
 , xdomain: !!headers.origin  // <Boolean> was it a cross domain request?
 , secure: socket.secure      // <Boolean> https connection
 , issued: +date              // <Number> EPOCH of when the handshake was created
 , url: request.url          // <String> the entrance path of the request
 , query: data.query          // <Object> the result of url.parse().query or a empty object
}

利用configure統一做一些處理

io.configure(function () {
    io.set('authorization', function (handshakeData, callback) {
        var ip = handshakeData.address.address;
        if (ip == '127.0.0.1') {
            //自訂handshakeData內容
            handshakeData.username = "Localhost";
        } else {
            handshakeData.username = "Johnson";
        }
        callback(null, true); // error first callback style
    });
});


io.sockets.on('connection', function (socket) {
    //handshake
    console.log(socket.handshake.username);
});
Categories: Node.js