Websocket在刷新时无法连接

I have got a Websocket server using Ratchet/PHP:

<?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();
?>

Mediator class:

<?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})
";
    }

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

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

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

Now on the client side, I have this basic JS code:

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

It does work (I can send and receive messages), however here's the problem:

When visiting the page for the first time, a connection with the websocket server is established and works fine. When I close the page, the connection is closed (as it should). However, when I refresh the page the connection is closed (on unloading the page, this is normal) but when the page is loaded again, no connection is made to the websocket server. I have to refresh again to make the script connect. This should not happen, right? I have no idea why this is happening, what's causing this.

douge3113
douge3113 我不太确定,使用不同的服务器会出现同样的问题。我尝试将C++和Node解决方案用于websocket服务器,除了描述的问题外,它们还可以工作。
一年多之前 回复
dsai1991
dsai1991 因此看起来服务器端存在一些问题,因为客户端已尝试建立连接但由于某种原因服务器没有响应
一年多之前 回复
dongyanpai2701
dongyanpai2701 >phpserver.php,Nginx也设置为反向代理,但我很确定这不是问题的一部分,因为它仍然存在而没有nginx。
一年多之前 回复
duanjiebian6712
duanjiebian6712 当连接工作时,它显示101状态代码。当我刷新(因此没有连接)时,状态保持在“待定”状态。
一年多之前 回复
dongyihao9887
dongyihao9887 你如何启动socketserver?
一年多之前 回复
dpwbc42604
dpwbc42604 Chrome中还有一个“网络”选项卡,您可以在其中查看打开控制台后所做的所有连接。所以打开这个并刷新网站然后尝试检查那里发生了什么
一年多之前 回复
duanjiong1952
duanjiong1952 刚刚发现在Firefox中没有任何连接,不确定是否与此有任何关系。由于我可以在Chrome中连接,因此在DevTools中,如果没有连接,则不会显示任何错误消息。所以我会尝试错误监听器
一年多之前 回复
douyue5856
douyue5856 看起来像浏览器中的一种错误或存在错误。我也会在websocket上创建一个错误监听器。有些错误可能无法建立套接字连接本身。
一年多之前 回复

1个回答

maybe add an event listener to close your ws javascript WebSocket before trying to reopen it.

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


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

also include possible console errors, as this looks like a issue with your javascript WebSocket logic, but I have been reading more info about Rachet/PHP and I would appreciate additional information on your backend logic.

Update

I suggest you to check out their demo page and debug both your code and your network requests. Start re-creating a 1-1 exactly identical working functionality, then implement your changes and understand what causes your errors:

1) Review your network request and persist the log, read them and report any strange issues

enter image description here

2) Review their code for the demo

enter image description here

dream07769
dream07769 是的我读了源代码。 在js方面我注意到在socket.me/vendor/web-socket.js里面他们使用window.Websocket = MozWebSocket for firefox,但我相信没有必要因为WebSocket应该与Firefox兼容。 他们的例子并不好,他们没有为你提供一个完整的例子,这个例子是用烧瓶建造的,而且是过度设计的。 他们在github.com/cboden/Ratchet-examples/tree/master/src上有几个例子,所以你可能想要分叉然后试一试
一年多之前 回复
douzhi3667
douzhi3667 我仍在查看代码,我注意到他们在演示中使用了Autobahn,所以我也会尝试这样做。 到目前为止我注意到的是在演示中服务器响应的Sec-WebSocketProtocol(设置为wamp),我错过了。 我不认为这是一个问题,因为连接永远不会到达服务器。
一年多之前 回复
dqenv99518
dqenv99518 我更新了答案谢谢
一年多之前 回复
duanqinqiao4844
duanqinqiao4844 你究竟想知道什么?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问