我使用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);
}
}
以下是请求标头(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.*"
}
}
答案 0 :(得分:3)
您正在错误地连接到websocket。 websocket不仅仅是您连接的文件,它必须是自己的进程。在命令行运行中,导航到存储的目录RatchetWebSocketServer.php
并运行
php RatchetWebSocketServer.php
然后在javascript中连接到127.0.0.1:8888
并且WebSocket应该可以工作。
不要忘记每次更改WebSocket代码时都需要停止php xx
命令并重新启动它。