2012-04-26 56 views
2

我有一個奇怪的問題。我正在編寫一個簡單的Socket.IO echo服務器作爲測試,但我無法使send()方法正常工作。在服務器上我使用這段代碼:Socket.IO send()不工作

var io = require('socket.io').listen(3000); 
var clients = {}; 

io.sockets.on('connection', function (socket) {  
     socket.send('test'); 

     socket.on('addclient', function(id) { 
      socket.id = id; 
      clients[id] = socket; 
      console.log('New client connected: '+ id); 
     }); 

     socket.on('echomessage', function(message) { 
      console.log('Sending echo message to client '+ socket.id); 
      socket.send(message); 
     }); 

     socket.on('disconnect', function() { 
      console.log('Client '+ socket.id + ' disconnected'); 
      delete clients[socket.id]; 
     }); 
}); 

的發送(「測試」)是可以正常使用,但是當我發出echomessage事件,我沒有收到該消息。服務器或客戶端沒有任何錯誤消息。

所以,在客戶方我這樣做:

// Connect with the server (works, connection established) 

// works too, I see it on the server 
sock.emit('addclient', 1); 

// I see 'Sending echo message to client 1' on the server 
sock.emit('echomessage', 'Echo this please'); 

但我完全不接收消息。

我完全不知道我做錯了什麼。所有幫助表示讚賞!

+0

檢查,如果他的客戶端連接到網絡插座,他只能放棄味精。 – 2012-04-26 15:18:07

+1

客戶端上的哪些代碼處理服務器發送的消息? – supertopi 2012-04-26 18:10:36

+0

我在客戶端上使用Java實現。客戶端已連接,因爲我從來沒有在客戶端或服務器端獲得「連接終止」消息。它似乎只是socket.send(消息);當echomessage事件被髮射時,一塊不起作用。 – EsTeGe 2012-04-29 12:26:40

回答

1

我相信你的錯誤是這裏的某個地方:

socket.on('addclient', function(id) { 
     socket.id = id; // <-- 
     clients[id] = socket; 
     console.log('New client connected: '+ id); 
    }); 

不要改變socket.id,因爲它是一個內部的,你可能會毀了使用插座的內部流程。

它由socket.io本身定義:source

+0

太棒了!這確實是問題。 – EsTeGe 2012-04-30 13:31:51