【发布时间】:2016-03-30 09:24:24
【问题描述】:
我已经尝试让 nginx/php 中的 websockets 工作好几天了。
这是我目前的设置:
'Chat.php' 路径 = root/src/MyApp/Chat.php
<?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) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
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();
}
}
'chat-server.php' 路径 = root/bin/chat-server.php
<?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()
)
),
8080
);
$server->run();
Nginx 配置
location / {
access_log off;
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
使用棘轮示例。我可以让正常的 CLI 消息正常工作。如果我在浏览器中尝试,控制台会弹出这个错误:
到 'ws://localhost:8080/' 的 WebSocket 连接失败:连接建立错误:net::ERR_CONNECTION_REFUSED
当时服务器确实在运行。有什么想法吗?
【问题讨论】:
-
我认为,Ratched 可以在没有 nginx 的情况下工作,我尝试在没有 nginx 的情况下进行调试,尝试检查端口是否打开(telnet localhost 8080)。没有nginx也可以(尝试在js中直接连接127.0.0.1和8080)?
-
您在浏览器中收到错误“WebSocket connection to 'ws://localhost:8080/' failed”,这意味着客户端直接连接到棘轮(端口 8080)。是这样吗?显示用于连接的 js 代码