我想创建一个连接到websocket服务器的PHP脚本,然后在本地websocket服务器上提供来自远程服务器的响应。基本上,websocket继电器。我有工作的客户端代码,我有工作的服务器代码。
当我尝试将客户端与服务器结合使用时出现问题。我已经尝试将我的客户端代码放入我的服务器代码中。它的工作原理除了客户端阻塞外,如果我断开它,我就无法重新连接。它发生在这样:
我开始使用我的代码 - >服务器代码打开本地端口并提供websocket - >我用websocket测试工具连接到本地端口 - >客户端代码连接到远程websocket服务器并中继对我的响应 - >我断开了我的工具 - >客户端代码永远不会返回,因此服务器代码不再接受新连接。
我的代码使用以下编写器包:
"cboden/ratchet": "^0.4.0",
"ratchet/pawl": "^0.3.1"
您可以看到我已注释掉连接到远程websocket服务器的客户端部分。这是阻止的部分。
<?php
// Make sure composer dependencies have been installed
require '../web/vendor/autoload.php';
require_once('../web/usersc/includes/custom_functions.php');
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use WebSocket\Client;
/**
* chat.php
* Send any incoming messages to all connected clients (except sender)
*/
class MyChat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
/*
$loop = React\EventLoop\Factory::create();
$reactConnector = new React\Socket\Connector($loop, [
'dns' => '8.8.8.8',
'timeout' => 10
]);
$connector = new Ratchet\Client\Connector($loop, $reactConnector);
$connector('wss://example.com/websocket', [], ['Origin' => 'http://localhost'])
->then(function(Ratchet\Client\WebSocket $conn) {
$conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "Received: {$msg}\n";
//$conn->close();
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
*/
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from != $client) {
$client->send($msg."sdfsfsf");
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat, array('*'));
$app->run();