user2264941
user2264941

Reputation: 407

Push message to websockets with ratchet php and without ZeroMQ

I try to make websocket server with rachet and pawl. I read doc ratchet with ZeroMQ http://socketo.me/docs/push But can't run it with Pawl https://github.com/ratchetphp/Pawl

I create client:

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

Create worker:

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 class usgin the same like in tutorial http://socketo.me/docs/push#zeromq_messages

Using post.php to send message through 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");

But still can't understand how to create tcp server withou ZeroMQ, like this part:

$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'));

Upvotes: 1

Views: 2876

Answers (2)

Eria
Eria

Reputation: 3182

If you don't wan't to use ZeroMQ, you can use the same React mecanisms Ratchet uses.

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();

Upvotes: 0

user2264941
user2264941

Reputation: 407

Doing with Pawl next and load on github: https://github.com/Shkarbatov/WebSocketPHPRatchet

Upvotes: 0

Related Questions