gpt4 book ai didi

javascript - Ratchet WebSocket(失败 : WebSocket opening handshake timed out)

转载 作者:行者123 更新时间:2023-11-30 12:17:17 25 4
gpt4 key购买 nike

我使用 Ratchet 和 JS 客户端创建了一个 websocket 服务器。每当 JS 客户端连接到服务器时,连接会空闲 4 分钟,然后才会给我握手超时。我试过禁用防火墙,更改端口,使用另一个 webBrowser,甚至尝试过在线教程,但到目前为止没有任何效果。请帮忙!

这是服务器代码:

<?php

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;

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

class RatchetWebSocketServer implements MessageComponentInterface{


public function onClose(ConnectionInterface $conn) {

}

public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->send($e->getMessage());
}

public function onMessage(ConnectionInterface $from, $msg) {
$from->send("Server returned : ".$msg);
}

public function onOpen(ConnectionInterface $conn) {

}

}


$server = IoServer::factory(new RatchetWebSocketServer(), 8888);
$server->run();

这是 JS 客户端代码:

function startServer(){
try{
var socket = new WebSocket("ws://127.0.0.1:80/CharlieTaxi/RatchetWebSocketServer.php");

socket.onopen = function(){

console.log("Socket Status: "+socket.readyState);
//send message to socket server
socket.send("Hello from Alfred to Server");
socket.close();
};

socket.onmessage = function(msg){
console.log(msg.data);
// socket.close();
};

socket.onclose = function(){
console.log('connection is closed!');
};
}
catch(e){
console.log(e);
}

}

这是请求 header (Chrome 浏览器):

Provisional headers are shown // this line is in bold with a yellow warning sign on the left
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8-
Cache-Control:no-cache
Connection:Upgrade
Cookie:PHPSESSID=pgo5ma6o5mlh6k9mtfcad4k6d4
Host:127.0.0.1
Origin:http://127.0.0.1
Pragma:no-cache
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
Sec-WebSocket-Key:sVGKPRvSUghm1xdCgBQCsA==
Sec-WebSocket-Version:13
Upgrade:websocket
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36

这是超时后的控制台输出:

WebSocket connection to 'ws://127.0.0.1/CharlieTaxi/RatchetWebSocketServer.php' failed: WebSocket opening handshake timed out

这是 composer.json 文件的内容:

{
"require": {
"cboden/ratchet": "0.3.*"
}
}

最佳答案

您未正确连接到您的 websocket。一个 websocket 不仅仅是一个你连接的文件,它必须是它自己的进程。在命令行运行中,导航到 RatchetWebSocketServer.php 存储的目录并运行

php RatchetWebSocketServer.php 文件

然后在 javascript 中连接到 127.0.0.1:8888 并且 WebSocket 应该可以工作。

不要忘记,每次更改 WebSocket 代码时,您都需要停止该 php xx 命令并重新启动它。

关于javascript - Ratchet WebSocket(失败 : WebSocket opening handshake timed out),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32116334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com