Ratchet Socket Hello wordをローカル マシンに実装しようとしていますが、すべてが完全に機能しますが、サーバー サービスを実行すると vps centos サーバー上で動作します
ssh Command : php chat-server.php
ポートでリッスンを正しく開始します(ポートがリッスンしていることがLinuxでわかります)が、「clint.html」ページを開くとメソッドは起動しonopen
ませんが、サーバーは言います
新しいクライアントが接続されました!
そして2分後にそれは言う
クライアントが切断されました
クライアントにメッセージを送信すると2分かかり、クライアントはそれを受信しますが、サーバーとクライアントの間に安定した接続がないように思えます。websocket.readyState をチェックするたびに 1 に等しくない
ファイアウォールと vps サーバーのセキュリティを無効にしましたが、まだこの問題があります。私はそれをテストでき、すべてが機能するので、通常のphpソケット機能は問題なく機能することに言及する必要があります
が、ラチェットについてはonopen
メソッドにハングしているようです。
- ポート 9091 が開いています
- ファイアウォールが無効になっています
- abrandao.com/2013/06/websockets-html5-php/ はホワイトアウトの問題を解決し、クライアントからメッセージを送受信できます
しかし、ラチェットには接続時に問題があります
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() }; }