我正在尝试在我的本地计算机上实现棘轮套接字Hello word,但是当我使用
运行服务器服务时,所有内容都能完美运行但是在vps centos服务器上ssh Command : php chat-server.php
它开始正确地侦听端口(我可以在linux上看到该端口正在侦听),但是当我打开" clint.html"页面方法onopen
永远不会触发,但服务器说
新客户连接!
并且在2分钟之后它说
客户端已断开连接
如果我向客户发送消息,则需要2分钟,然后客户端才会收到消息,但会再次断开连接
在我看来,服务器和客户端之间没有稳定的连接。每当我检查websocket.readyState时它不等于1
我禁用了防火墙和vps服务器上的任何安全性,但仍然有这个问题。
我必须提到正常的php套接字函数没有问题,因为我可以测试它并every thing works
但关于棘轮似乎它挂在onopen
方法上。
但棘轮连接有问题
chat-server.php:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
9091
);
echo date("Y-m-d H:i:s")." chat-server Started on port 9091 \n";
$server->run();
Chat.php类:
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo date("Y-m-d H:i:s")." New connection! ({$conn->resourceId})\n";
$conn->send("Hello {$conn->resourceId} from server at : ".date("Y-m-d H:i:s"));
echo date("Y-m-d H:i:s")." Hello Sent to ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf(date("Y-m-d H:i:s").'Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo date("Y-m-d H:i:s")." Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo date("Y-m-d H:i:s")." An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
客户端html:
$(document).ready(function(){
connect();
});
var wsUri = "ws://myserverdomain.comOrIP:9091";
function connect() {
var ws = new WebSocket(wsUri);
ws.onopen = function() {
var now = new Date();
console.log(now + ' Connected to '+wsUri);
};
ws.onmessage = function(e) {
var now = new Date();
console.log(now + ' Message Recived From Server :', e.data);
};
ws.onclose = function(e) {
var now = new Date();
console.log(now +' Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000)
};
ws.onerror = function(err) {
var now = new Date();
console.error(now + ' Socket encountered error: ', err.message, 'Closing socket')
console.error(err)
ws.close()
};
}