棘轮:如何在同一台服务器上使用聊天和推送通知

时间:2015-06-24 08:51:39

标签: php websocket

我想在同一台服务器上使用来自棘轮教程(http://socketo.me)的两个应用程序“chat”和“push notifications” - “Hello world”(http://socketo.me/docs/hello-world) - 与ZMQ“推动整合” 每个应用程序运行良好,我运行chat-server.php(用于聊天)和push-server.php(用于推送集成)。但是当我打开两个cmd窗口并运行它们时它不起作用。这可能是一个愚蠢的问题,但我是这个领域的初学者。

在下面找到两个可执行文件的代码

chat-server.php:

使用Ratchet \ Server \ IoServer; 使用MyApp \ Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new Chat(),
    8080
);

$server->run();

push-server.php:

require dirname(__DIR__) . '/vendor/autoload.php';

$loop   = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

提前感谢您的帮助。让我知道如果您需要更多信息

1 个答案:

答案 0 :(得分:0)

您可以使用单独的文件 chat-server.php push-server.php ,但不能从两个不同的文件监听同一端口。您将不得不更改其中之一。您可以将 push-server.php 的端口保留为8080,并将 chat-server.php 的端口更改为3000(例如):

use Ratchet\Server\IoServer; use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new Chat(),
    3000
);

$server->run();

如果您要使用一个服务器文件,这很简单,只需将 chat-server.php 中的一行添加到 push-server.php中(我在旁边写了一条评论)。因此,您的最终文件将如下所示:

require dirname(__DIR__) . '/vendor/autoload.php';

$loop   = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new MyApp\Chat(), // This is the line added
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

请勿添加 server.php 中的其他任何内容,例如use ...;

请确保您分别拥有文件{strong> /src/MyApp/Chat.php 和 /src/MyApp/Pusher.php ,文件分别为Chat和{ {1}}。

现在运行时:

Pusher

它将执行 server.php 所做的任务。