簡體   English   中英

Websocket在刷新時無法連接

[英]Websocket does not connect on refresh

我有一個使用Ratchet / PHP的Websocket服務器:

<?php
require __DIR__.'/../vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Mediator;

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Mediator()
        )
    ),
    9000
);

$server->run();
?>

調解員班:

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Mediator implements MessageComponentInterface {
    protected $clients = [];

    public function onOpen(ConnectionInterface $conn) {
        $this->clients[$conn->resourceId] = $conn;
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        echo "Incoming: $msg\n";
    }

    public function onClose(ConnectionInterface $conn) {
        unset($this->clients[$conn->resourceId]);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

現在在客戶端,我有這個基本的JS代碼:

let ws = new WebSocket('wss://localhost:8443');
ws.addEventListener('open', () => {
    ws.send('Hello!');
});
ws.addEventListener('message', event => {
    alert(event.data);
});

它確實有效(我可以發送和接收消息),但問題是:

首次訪問該頁面時,建立與websocket服務器的連接並正常工作。 當我關閉頁面時,連接將關閉(應該如此)。 但是,當我刷新頁面時,連接被關閉(在卸載頁面時,這是正常的)但是當再次加載頁面時,沒有與websocket服務器建立連接。 我必須再次刷新以使腳本連接。 這不應該發生,對吧? 我不知道為什么會發生這種情況,導致這種情況的原因。

也許添加一個事件監聽器來關閉你的ws javascript WebSocket然后再嘗試重新打開它。

let ws = new WebSocket('wss://localhost:8443');
ws.addEventListener('open', () => {
    ws.send('Hello!');
});


$(window).unload(function () {
   ws.close();
});

還包括可能的控制台錯誤,因為這看起來像你的javascript WebSocket邏輯的問題,但我一直在閱讀有關Rachet / PHP的更多信息 ,我將非常感謝有關你的后端邏輯的更多信息。

更新

我建議你查看他們的演示頁面並調試你的代碼和你的網絡請求。 開始重新創建1-1完全相同的工作功能,然后實施更改並了解導致錯誤的原因:

1)檢查您的網絡請求並保留日志,閱讀並報告任何奇怪的問題

在此輸入圖像描述

2)查看他們的演示代碼

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM