問題描述
我正在使用使用 PHP5 和 Chrome 瀏覽器作為客戶端的網絡套接字.我從網站 http://code.google.com/p/phpwebsocket/一>.
I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.
我運行服務器,客戶端也連接上了.我也可以聊天.現在,當我重新啟動服務器(通過殺死它并重新啟動它)時,客戶端獲取斷開連接的信息,但當我發送消息時不會自動重新連接服務器.
I run the server, and the client is also connected. I can chat as well. Now when I restart the server (by killing it and starting it again), the client gets the disconnected information, but automatically doesn't reconnect with server when I send the message.
如何實現?比如當我得到斷開連接的信息時,我應該檢查它并將其發送給 JavaScript 刷新頁面還是重新連接?
How to achieve this? Like when I get the dis-connected information, should I check it and send it to JavaScript to refresh the page or reconnect?
推薦答案
當服務器重啟時,Web Socket 連接關閉,因此觸發 JavaScript onclose
事件.這是一個每五秒嘗試重新連接一次的示例.
When the server reboots, the Web Socket connection is closed, so the JavaScript onclose
event is triggered. Here's an example that tries to reconnect every five seconds.
function start(websocketServerLocation){
ws = new WebSocket(websocketServerLocation);
ws.onmessage = function(evt) { alert('message received'); };
ws.onclose = function(){
// Try to reconnect in 5 seconds
setTimeout(function(){start(websocketServerLocation)}, 5000);
};
}
這篇關于服務器在 WebSocket 中重新啟動時重新連接客戶端的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!