使用棘轮式php和不使用ZeroMQ将消息推送到websockets

时间:2018-08-17 11:41:32

标签: php websocket ratchet reactphp

我尝试用棘轮和棘爪制作websocket服务器。 我使用ZeroMQ http://socketo.me/docs/push阅读了文档棘轮文章 但是无法与Pawl https://github.com/ratchetphp/Pawl

一起运行

我创建客户端:

<script>
    var ws = new WebSocket('ws://site.ll:8008/?user=tester01');
    ws.onmessage = function(evt) { console.log(evt.data); };
</script>

创建工作人员:

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Pusher.php';

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

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8008', $loop);

$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

Pusher类的用法与教程http://socketo.me/docs/push#zeromq_messages

中的相同

使用post.php通过ws发送消息:

$localsocket = 'tcp://127.0.0.1:1235';
$user = 'tester01';
$message = 'test';

$instance = stream_socket_client($localsocket);
fwrite($instance, json_encode(['user' => $user, 'message' => $message])  . "\n");

但是仍然无法理解如何使用ZeroMQ创建tcp服务器,就像这部分一样:

$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:1235');
$pull->on('message', array($pusher, 'onBlogEntry'));

2 个答案:

答案 0 :(得分:1)

如果您不想使用ZeroMQ,则可以使用Ratchet使用的相同的React机制。

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Pusher.php';

use React\EventLoop\Factory;
use React\Socket\ConnectionInterface;
use React\Socket\Server;

$loop   = Factory::create();
$pusher = new Pusher;

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

// Set up an incoming TCP socket to receive the messages to push
$inSocket = new Server('127.0.0.1:5555', $loop);
$inSocket->on('connection', function (ConnectionInterface $conn) use ($pusher) {
    // New data arrives at the socket
    $conn->on('data', function ($data) use ($conn, $pusher) {
        // Push the new blog entry update
        $pusher->onBlogEntry($data);
        // Close the incoming connection when the message is consumed
        $conn->close();
    });
});

$loop->run();

答案 1 :(得分:0)

接下来使用Pawl并在github上加载: https://github.com/Shkarbatov/WebSocketPHPRatchet