我设法创建了一个Web服务,它在端口80上侦听http请求并处理ajax调用和长轮询。
但我仍然坚持在同一个php文件中创建类似的websocke服务器
<?php
require_once('vendor/autoload.php');
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
$conn->send('aa');
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('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) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$loop = React\EventLoop\Factory::create();
$swsa=new Chat;
$webSock = new React\Socket\Server($loop);
$webSock->listen(8687, '127.0.0.1'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
$swsa
)
),
$webSock
);
$app = function ($request, $response) {
//some code here to manage requests
$response->writeHead(200,array('Content-Type'=>'application/json'));
$response->end(json_encode(array('ok'=>'ok')));
};
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
$socket->listen(8485);
$loop->run();
浏览器中的代码:
var wsUri = "ws://127.0.0.1:8687/";
websocket = new WebSocket(wsUri);
这会在浏览器中触发错误
Firefox can't establish a connection to the server at ws://127.0.0.1:8687/
答案 0 :(得分:1)
您的IoServer初始化不正确。如果检查IoServer类的代码,您会发现:
public function __construct(MessageComponentInterface $app,ServerInterface $socket, LoopInterface $loop = null)
和
public function run() {
if (null === $this->loop) {
throw new \RuntimeException("A React Loop was not provided during instantiation");
}
// @codeCoverageIgnoreStart
$this->loop->run();
// @codeCoverageIgnoreEnd
}
IoServer类对象没有为其分配循环,因此无法执行。尝试将循环作为第三个参数传递。