Nginx PHP网络套接字问题


Nginx PHP websocket issues

我已经试着让nginx.php中的websocket工作了好几天了。

这是我目前的设置:

"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-serverphp

<?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 conf

 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

服务器当时确实在运行。有什么想法吗?

您必须使用从浏览器访问您的websocket

new WebSocket('ws://localhost/');

然后,Nginx将这个请求(/上的任何请求)代理到http://localhost:8080;,您的PHP websocket实现正在那里侦听…希望