Ratchet Websocket – ZMQ push

install zmq and php biding

you had success install zmq and php-biding, and get the source via composer

source-ratchet

begin create ‘push’


# to folder code

$ cd /media/sf_websocket/push

# create folder src/MyApp

$ mkdir src/MyApp -p

# create file Pusher.php

$ nano src/MyApp/Pusher.php

paste this code to Pusher.php


<?php
namespace MyApp;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class Pusher implements WampServerInterface {
    
    /**
     * A lookup of all the topics clients have subscribed to
     */
    protected $subscribedTopics = array();
    
    public function onSubscribe(ConnectionInterface $conn, $topic) {
        $this->subscribedTopics[$topic->getId()] = $topic;
    }
    
    /**
     * @param string JSON'ified string we'll receive from ZeroMQ
     */
    public function onBlogEntry($entry) {
        $entryData = json_decode($entry, true);
    
        // If the lookup topic object isn't set there is no one to publish to
        if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
            return;
        }
    
        $topic = $this->subscribedTopics[$entryData['category']];
    
        // re-send the data to all the clients subscribed to that category
        $topic->broadcast($entryData);
    }
    
    /* The rest of our methods were as they were, omitted from docs to save space */
    
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    
    }
    
    public function onOpen(ConnectionInterface $conn) {
    
    }
    
    public function onClose(ConnectionInterface $conn) {
    
    }
    
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
    }
    
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->close();
    }
    
    public function onError(ConnectionInterface $conn, \Exception $e) {
    }
}

create folder client, we will place this folder for all client side script


$ cd /media/sf_websocket/push

$ mkdir client

$ nano client/form.html

paste this code to client/form.html


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>form ui</title>

</head>
<body>

<div class='container'>
    <input type='text' id='category' placeholder='category' value='kittensCategory' /><br />
    <input type='text' id='title' placeholder='title' value='' /><br />
    <textarea id='article' cols='25' rows='5'></textarea><br />
    <button id='btn-simpan' class='btn-success btn-xs'>Simpan</button>
</div>
<script src"//code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script></pre>
<pre>
<script>
$(document).ready(function(){
    //console.log('ok coy');
    
});
$('#btn-simpan').click(function(){
    //console.log('di click');
    $.post('post.php',
        {
            category:$('#category').val(),
            title:$('#title').val(),
            article:$('#article').val()
        },
        function(d){
            console.log(d);
        }
    );
});
</script>
</body>
</html>

create post.ph


$ nano client/post.php

paste to client/post.php


<?php
    // post.php ???
    // This all was here before 😉
    $entryData = array(
        'category' => $_POST['category']
      , 'title'    => $_POST['title']
      , 'article'  => $_POST['article']
      , 'when'     => time()
    );
    print_r($entryData);
    #$pdo->prepare("INSERT INTO blogs (title, article, category, published) VALUES (?, ?, ?, ?)")
    #    ->execute($entryData['title'], $entryData['article'], $entryData['category'], $entryData['when']);

    // This is our new stuff
    
    $context = new ZMQContext();
    $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
    $socket->connect("tcp://localhost:5555");

    $socket->send(json_encode($entryData));
    

create file client/push-view.html


$ nano client/push-view.html

paste this code


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<div class='container-fluid'>
    <div id='msg-push' class=''></div>
</div>

<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<div class="container">
<div class="line">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<script>
    var conn = new ab.Session('ws://192.168.1.196:8080',
        function() {
            conn.subscribe('kittensCategory', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                var a = '<div class="btn-info col-xs-8">'+'New article published to category "' + topic + '" : ' + data.title+'</div>'
                $('#msg-push').prepend(a);
            });
        },
        function() {
            console.warn('WebSocket connection closed');
        },
        {'skipSubprotocolCheck': true}
    );
</script>

</body>
</html>

now create bin/push-server.php


$ cd /media/sf_websocket/push

$ mkdir bin

$ nano bin/push-server.php

paste code to bin/push-server.php


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

now running server


$ cd /media/sf_websocket/push

$ php bin/push-server.php

open via browser url your ip server

http://192.168.1.196/push/client/form.html

and

http://192.168.1.196/push/client/push-view.html

 

zmq-push

and finish folder

zmq-push-folder-finish

Published by

G3n1k

just to remember what i had known :)

3 thoughts on “Ratchet Websocket – ZMQ push”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s