問題描述
我正在使用使用 PHP5 和 Chrome 瀏覽器作為客戶端的網(wǎng)絡(luò)套接字.我從網(wǎng)站 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/.
我運行服務(wù)器,客戶端也連接上了.我也可以聊天.現(xiàn)在,當(dāng)我重新啟動服務(wù)器(通過殺死它并重新啟動它)時,客戶端獲取斷開連接的信息,但當(dāng)我發(fā)送消息時不會自動重新連接服務(wù)器.
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.
如何實現(xiàn)?比如當(dāng)我得到斷開連接的信息時,我應(yīng)該檢查它并將其發(fā)送給 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?
推薦答案
當(dāng)服務(wù)器重啟時,Web Socket 連接關(guān)閉,因此觸發(fā) 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);
};
}
這篇關(guān)于服務(wù)器在 WebSocket 中重新啟動時重新連接客戶端的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!