2011-05-23 250 views
3

我使用ws library爲的WebSockets在Node.js和受 我試圖從圖書館的例子這個例子:的Node.js的WebSocket廣播

var sys = require("sys"), 
    ws = require("./ws"); 

    ws.createServer(function (websocket) { 
    websocket.addListener("connect", function (resource) { 
     // emitted after handshake 
     sys.debug("connect: " + resource); 

     // server closes connection after 10s, will also get "close" event 
     setTimeout(websocket.end, 10 * 1000); 
    }).addListener("data", function (data) { 
     // handle incoming data 
     sys.debug(data); 

     // send data to client 
     websocket.write("Thanks!"); 
    }).addListener("close", function() { 
     // emitted when server or client closes connection 
     sys.debug("close"); 
    }); 
    }).listen(8080); 

一切OK。它工作,但運行3個客戶端,例如,併發送「你好!」從一個將使服務器只回復「謝謝!」給發送消息的客戶,而不是全部。

如何播放「謝謝!」當有人發送「你好!」時所有連接的客戶端?

謝謝!

回答

3

我建議你使用socket.io。它具有開箱即用的示例網絡聊天功能,還提供客戶端套接字技術的抽象層(WebSocket由Safari,Chrome,Opera和Firefox支持,但由於ws協議中的安全漏洞,現在在Firefox和Opera中被禁用)。

+1

感謝您的建議,回答,但我認爲1年後(+/-)所有瀏覽器的支持WebSocket的。 :-) – vhyea 2011-05-23 14:22:26

+0

Chrome和Firefox r支持Websockets(儘管在FF中默認禁用) – Matt 2011-05-23 14:33:33

+0

@Matt編輯了答案的文本。 – bjornd 2011-05-23 14:38:03

8

如果你想發送給所有的客戶,你必須跟蹤他們。這裏是一個樣本:

var sys = require("sys"), 
    ws = require("./ws"); 

// # Keep track of all our clients 
var clients = []; 

    ws.createServer(function (websocket) { 
    websocket.addListener("connect", function (resource) { 
     // emitted after handshake 
     sys.debug("connect: " + resource); 

     // # Add to our list of clients 
     clients.push(websocket); 

     // server closes connection after 10s, will also get "close" event 
     // setTimeout(websocket.end, 10 * 1000); 
    }).addListener("data", function (data) { 
     // handle incoming data 
     sys.debug(data); 

     // send data to client 
     // # Write out to all our clients 
     for(var i = 0; i < clients.length; i++) { 
    clients[i].write("Thanks!"); 
     } 
    }).addListener("close", function() { 
     // emitted when server or client closes connection 
     sys.debug("close"); 
     for(var i = 0; i < clients.length; i++) { 
     // # Remove from our connections list so we don't send 
     // # to a dead socket 
    if(clients[i] == websocket) { 
     clients.splice(i); 
     break; 
    } 
     } 
    }); 
    }).listen(8080); 

我能夠得到它廣播給所有的客戶端,但它沒有嚴格測試所有情況下。一般的概念應該讓你開始。

編輯:順便說一句,我不知道10秒關閉是什麼,所以我評論它。如果您試圖向所有客戶進行廣播,因爲它們會一直斷開連接,這是毫無用處的。

+0

onteria_,非常感謝!工作!我開始了! :-) 謝謝(和所有其他的謝謝你的答案),祝你好運! – vhyea 2011-05-23 15:04:29