2017-09-01 86 views
1

我要當一個REST API稱爲數據推送到網絡插座通過觸發外部

我有一個基於明確節點JS應用程序將數據推送到所有連接的插座。

在應用程序啓動時,我創建了文檔中提到的套接字服務器。

客戶端代碼

var socket = io('http://localhost'); 
socket.emit('client_id', 'test'); 
socket.on('message', function (message) { 
    console.log(message); 
}); 

服務器代碼

io.on('connection', function (socket) { 
    socket.on('client_id', function (client_id) { 
     socket.join(client_id); 
    }); 
}); 

API調用

io.sockets.to('client_name').emit('message', 'Some message'); 

這個問題我s,這工作正常,當我啓動節點/套接字服務器並啓動客戶端。

但是,當我重新啓動節點/套接字服務器時,客戶端不再接收消息。我將不得不重新加載客戶端以開始接收消息。

可能是什麼問題

+0

你能提供你的客戶端代碼嗎?您是使用'socket.io'客戶端還是[WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)? – codtex

+0

正如我所提到的,無論在文檔中提到什麼。任何方式..只是更新 – madhairsilence

+0

當我在兩側使用'socket.io'庫,當我停止服務器並再次運行時,所有客戶端自動連接。問題可能來自應用程序設計。 – codtex

回答

2

所以在commented的問題下,我會嘗試解釋你提供的代碼究竟發生了什麼。此外,我想了一個辦法,提出你your comment

// With the following line of code you connect to the server 
var socket = io('http://localhost'); 

// Now you send the client_id and it is sent only once per page load 
socket.emit('client_id', 'test'); 

// And here subscribe to the message event 
socket.on('message', function (message) { 
    console.log(message); 
}); 

// ---------------------------------------- 
// now we change the above code like 

var socket = io('http://localhost'); 
socket.on('connect', function(){ 
    // emit the event client_id every time you connect 
    socket.emit('client_id', 'test'); 
    socket.on('message', function (message) { 
     console.log(message); 
    }); 
}); 

您需要包裝內on('connect', ...)申購代碼,以確保每一個你連接到服務器client_id時間被髮送。否則當客戶端代碼被加載時,client_id只發送一次。

如果你想避免雙重信息,如your comment所述,您可以更新服務器端代碼,如:

// Save reference to client_id by socket.id 
var clientIds = {}; 
io.on('connection', function (socket) { 

    socket.on('client_id', function (client_id) { 
     clientIds[socket.id] = client_id; 
     socket.join(client_id); 
    }); 

    // Subscribe to disconnect event and leave the room once client is disconnected 
    socket.on('disconnect', function (reason) { 
     // leave the room 
     socket.leave(clientIds[socket.id]); 
    }); 

}); 

與上面的代碼,你確保你離開房間,一旦一個客戶端斷開連接。

讓我知道如果有什麼不清楚。祝你好運!

+0

這清除了事情。非常感謝。總結一下。 1.將代碼置於'連接'內,2.在頁面刷新期間使用'socket.id'手動刪除連接,以避免連接重複; – madhairsilence

+0

不客氣,朋友。我很高興這是有幫助的:) – codtex

-2

每個網絡連接都有一個與之相關的一些狀態,當你重新啓動服務器,你最有可能失去。實現超時並重新連接到服務器是一種可能的解決方案。