EzDev.org

ratchet

Build mobile apps with simple HTML, CSS, and JavaScript components. Ratchet ratchet: build mobile apps with simple html, css, and js components.


Ratchet / When.js: "Uncaught ReferenceError: module is not defined"

I'm trying to use ratchet for reflecting the changes made to my database realtime. I used the code of the pusher app (http://socketo.me/docs/push). But i am getting error in that.

The moment I open the client side page :

Uncaught ReferenceError: module is not defined                    when.js:900
(anonymous function)                                              when.js:900
(anonymous function)                                              when.js:15
(anonymous function)                                              when.js:900

After this I typed: conn.subscribe('topic'); //This subscribes the topic.

Now the moment I make changes to this topic, an error pops up where the changes are to be displayed.

Error 2 :

Uncaught TypeError: undefined is not a function         [VM] autobahn.min.js (124):66
(anonymous function)                                    [VM] autobahn.min.js (124):66
c._websocket.onmessage                                  [VM] autobahn.min.js (124):66

Any help ?


Source: (StackOverflow)

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I try to connect with socket to my server. My server is running server socket with Rachet on port 8080. I try to run this code:

<script>   

    try{
    conn = new WebSocket('wss://localhost:8080');


conn.onclose = function (e)
{
        //checkUser();
}

conn.onopen = function(e) 
{
    console.log("test");
};

    }catch (error)
{
    console.log(error);
}

  </script>

But I get this error:

WebSocket connection to 'wss://localhost:8080/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

When I try to connect from my linux shell I get this:

root@(none):~# telnet localhost 8080
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Source: (StackOverflow)

PHP WebSockets with Ratchet - example doesn't work

Here's some background first.

1) My aim is to use Ratchet WebSockets to create two-way client-server communication.

2) I have installed ratchet and accompanying software, as described here.

3) I have successfully created a Hello World application as described here.

4) Now I am trying to create Push functionality using this tutorial. I have copied the code, modifying it slightly (modifications noted in code comments below), installed the ZMQ library (latest version, added it to php.ini, show up in php -m - in short, it's installed correctly). But the WebSockets don't work.

I will give my testing process with real live links to my domain below, so you can check it yourself.

1) My push server is exactly the same as the one in their tutorial, with the IP changed to my server's IP. I run this through SSH and it seems to connect correctly.

2) My Pusher class is in the MyApp namespace, same code and same relative location as in their tutorial.

3) My post.php is slightly modified because there's no need to bother with MySQL queries:

$entryData = array(        //hard-coded content of $entryData for simplicity
    'cat'     => "macka"
  , 'title'   => "naslov"
  , 'article' => "tekst"
  , 'when'    => time()
);

// This is our new stuff
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://light-speed-games.com:5555");       //my domain, still using port 5555 as in their example

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

This file is located here.

4) My client.php is the same as theirs, except I had to add a little fix for IE to work with when.js. My problem is browser-independent and the same as it was before the fix was added.

<script>
    window.define = function(factory) {    //my addition
        try{ delete window.define; } catch(e){ window.define = void 0; } // IE
        window.when = factory();
    };
    window.define.amd = {};
</script>
<script src="/apps/scripts/when.js"></script> 
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
    var conn = new ab.Session(
        'ws://light-speed-games.com:8080' // The host (our Ratchet WebSocket server) to connect to
      , function() {            // Once the connection has been established
            conn.subscribe('kittensCategory', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                console.log('New article published to category "' + topic + '" : ' + data.title);
            });
        }
      , function() {            // When the connection is closed
            console.warn('WebSocket connection closed');
        }
      , {                       // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
            'skipSubprotocolCheck': true
        }
    );
</script>

This file is located here.

In theory, what should happen is this (for example): I open client.php in Chrome with console switched on; then I open post.php in Firefox; Chrome's console should show the message 'New article published...' etc (from the conn.subscribe function in client.php). However, when I do this, nothing happens. The connection remains open (doesn't show the 'connection closed' error until I switch off push-server.php through SSH). The console remains empty.

I think that's all the relevant info from the last couple of days, a large portion of which I've spent on trying to figure this out. However, I've been unable to even make sure if the problem is with the code or with some server configuration setting I may be unaware of. So, I come to you hoping someone will point me in the right direction.

IMPORTANT EDIT:

I'm pretty sure the problem is with the Autobahn.js method conn.subscribe not working properly. The connection is being established. When I change the code to:

function() {            // Once the connection has been established
            console.log('Connection established');
            conn.subscribe('kittensCategory', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                console.log('New article published to category "' + topic + '" : ' + data.title);
            });
        }

Then Connection established is shown in the console correctly. So I believe we need to troubleshoot the subscribe method. If someone can explain to me how it works, and what exactly "topic" and "data" are supposed to be, ti would be of great help. The Autobahn documentation uses a URL as an argument for this method (see here).


Source: (StackOverflow)

Node.js with Laravel 4.2

I currently working on php project - Laravel 4.2 framework. I need to use node.js. Need to real time update count of users that registered, on dashbord.

I tried with Ratchet , but I'm not clear following file path that we must edit.

  • /src/MyApp/Chat.php
  • /bin/chat-server.php

Does someone have experience working with node.js on Laravel? Please help me.


Source: (StackOverflow)

Using PHP Pthreads with Ratchet Websocket

I am making an html5 game www.titansoftime.com

I am using ratchet as a php websocket server solution. It works great! http://socketo.me/docs/push

I have done several standalone test using the php pthreads extension and have seen some very exciting results. It truly works and works well.. as long as websockets aren't in the mix.

Pthreads give php multithreading capabilities (it really does work and it's amazing). http://php.net/manual/en/book.pthreads.php

This is what I do:

/src/server.php This is the file that launches the daemon.

    <?php
    session_start();

    use Ratchet\Server\IoServer;
    use Ratchet\WebSocket\WsServer;
    use MyApp\Pusher;

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

    require_once __DIR__ . '/../mysql.cls.php';
    require_once __DIR__ . '/../game.cls.php';
    require_once __DIR__ . '/../model.cls.php';

    $mysql = new mysql;
    $game  = new game;

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

    $loop->addPeriodicTimer(0.50, function() use($pusher){
        $pusher->load();
    });

    $webSock = new React\Socket\Server($loop);

    if ($loop instanceof \React\EventLoop\LibEventLoop) {
        echo "\n HAS LibEvent";
    }

    $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($pusher)
            ),
            $webSock
    );

    $loop->run();

This all works fine.

/src/MyApp/Pusher.php This class pushes data to all connected users.

<?php
namespace MyApp;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;

class AsyncThread extends \Thread{

    public $client;

    public function __construct($client){
        $this->client = $client;
    }

    public function run(){

        // do work on $this->client
        $user = mysql::assoc('SELECT * from users WHERE connection_id = "'.$this->client->resourceId.'"');
        // etc..
        $this->client->send(json_encode(array('foo'=>'bar')));

    }

}

class Pusher implements MessageComponentInterface{

    public static $clients = array();

    #load
    public static function load(){

        $client_count = count(self::$clients);

        echo "\n\n\n".'Serving to '.$client_count.' clients. '.time();

        $start = $istart = microtime(true);

        if( !count(self::$clients) ){
            if( !mysql_ping() ){
                $game->connect();
            }
        }

        $threads = array();
        foreach( self::$clients as $key => $client ){       

            // HANDLE CLIENT

            // This works just fine, the only problem is that if I have lets say 50 simultaneous users, the people near the end of the clients array will have to wait till the other users have been processed. This is not desirable
            $client->send(json_encode('foo'=>'bar'));

           // So I tried this:
           $threads[$key] = new AsyncThread($client);
           $threads[$key]->start();

           // At this point the AsyncThread class will throw a fatal error complaining about not being able to serialize a closure. 
          // If I dont set "$this->data = $client;" in the thread constructor no error appears but now I cant use the data.

           // Also regardless of whether or not I bind the data in the AsyncThread constructor,
           // the connection disappears if I call "new AsyncThread($client)". I cannot explain this behavior.

        }

    }

    public function onMessage(ConnectionInterface $from, $msg) {
        global $game;
        if( $msg ){
            $data = json_decode($msg);
            if( $data ){    

                switch( $data->task ){

                    #connect
                    case 'connect':
                        echo "\n".'New connection! ('.$from->resourceId.') '.$from->remoteAddress;
                        self::$clients[] = $from;
                        break;

                    default:
                        self::closeConnection($from);
                        echo "\nNO TASK CLOSING";
                        break;

                }
            }else{
                echo "\n NO DATA";
                self::closeConnection($from);
            }
        }else{
            echo "\n NO MSG";
            self::closeConnection($from);
        }
    }

    public function closeConnection($conn){
        global $game;
        if( $conn ){
            if( $conn->resourceId ){
                $connid = $conn->resourceId;
                $conn->close(); 
                $new = array();
                foreach( self::$clients as $client ){
                    if( $client->resourceId != $connid ){
                        $new[] = $client;
                    }
                }
                self::$clients = $new;
                $game->query('UPDATE users set connection_id = 0 WHERE connection_id = "'.intval($connid).'" LIMIT 1');
                echo "\n".'Connection '.$connid.' has disconnected';
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        echo "\nCLIENT DROPPED";
        self::closeConnection($conn);
    }

    public function onOpen(ConnectionInterface $conn) {
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "\nCLIENT ERRORED";
        self::closeConnection($conn);
    }
    public function onSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
    }

}

This all works fine as long as I don't create a thread inside the event loop.

Am I going about this the wrong way or is php multithreading and websockets incompatible?


Source: (StackOverflow)

Uncaugth reference error custom event not defind in the file ratchet

Hai i am new in phonegap and ratchet framework.I am trying to load external script with push.js. Here is my js file contents

function init(){
    document.addEventListener('deviceready', onDeviceReady, false);

    function onDeviceReady(){

        alert("device ready for use");
        }
       var checkPage = function(){

        alert("push");
        var scriptName; 
        var scriptsList = document.querySelectorAll('script.js-custom');  // Add a "js-custom" class to your script tag
        for (var i = 0; i<scriptsList.length;i++) {

            // Handle scripts in separate files by assigning the script file name to its id.
            // We save it in a variable because the ".done" callback is asynchronous.
            scriptName = scriptsList[i].id;  // IMPORTANT: Only one loadable script per page!
            $.getScript("js/" + scriptName)
              .done(function (script, textStatus) {
                  eval(script);
                  alert("ok");
              })
              .fail(function(){
                  alert("error");
              });

        }


    };   

    window.addEventListener('push', checkPage);

    } 

Here is my html file

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">  
    <title>Ratchet template page</title>

    <!-- Sets initial viewport load and disables zooming  -->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

    <!-- Makes your prototype chrome-less once bookmarked to your phone's home screen -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <!-- Include the compiled Ratchet CSS -->
    <link rel='nofollow' href="css/ratchet.min.css" rel="stylesheet">

    <!-- Include the compiled Ratchet JS -->
    <script src="js/ratchet.min.js"></script> 
    <script src="js/jquery.js"></script>
     <script src="cordova.js"></script>

  </head>
  <body onload="init()">  

    <!-- Make sure all your bars are the first things in your <body> -->
    <header class="bar bar-nav">
      <h1 class="title">Ratchet</h1>
    </header>

    <!-- Wrap all non-bar HTML in the .content div (this is actually what scrolls) -->
    <div class="content">

      <div class="card">
        <ul class="table-view">
          <li class="table-view-cell">

            <a class="push-right" rel='nofollow' href="two.html">
              <strong>Another page</strong>
            </a>
          </li>  
          <li class="table-view-cell"> 
            <a class="push-right" rel='nofollow' href="https://github.com/twbs/ratchet/">
              <strong>Ratchet on Github</strong>
            </a>

      </div>
    </div>

Here is my two.html file

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Notes</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <!-- Roboto
    <link rel="stylesheet" rel='nofollow' href="//fonts.googleapis.com/css?family=Roboto:400,500,700"> -->

    <link rel="stylesheet" rel='nofollow' href="ratchet.min.css">
    <script src="ratchet.min.js"></script>
  </head>
  <body>
      <header class="bar bar-nav">
  <h1 class="title">Two</h1>
    </header>
  </body>
  <div class="content">
  <script src="js/sample.js" class="js-custom" id="sample.js"></script>
  </div>
</html>

But i run the project i get

Uncaught ReferenceError: CustomEvent is not defined at file:///android_asset/www/js/ratchet.min.js:10

please help me.


Source: (StackOverflow)

Ratchet / Websockets : How many clients subscribing to an object?

I would like to know how many clients are actually subscribing to a chatroom / conversation.

To be more precise, i just want to know if there is more than 1 client. (Chatroom are actually a private conversation between two users).

There is only one chatroom / private conversation at a time (per user).

class Chat implements WampServerInterface
{
    protected $conversationId;
    public function __construct(){
        $this->conversationId = null;
    }
    public function onSubscribe(ConnectionInterface $conn, $conversation_id){
        $this->conversationId = $conversation_id;
        echo "Client $conn->resourceId assigned to the conversation : $conversation_id\n";
    }
    public function onPublish(ConnectionInterface $conn, $conversation_id, $event, array $exclude, array $eligible){
        // How to get $nb_clients ?
        echo "$nb_clients User(s) in conversation";
        echo "Message sent to $conversation_id : $event";
        // ...
        $message = $event; 
        // Send data to conversation
        $this->conversationId->broadcast($message);
    }
}

So in the given code, how to get $nb_clients?


Update:

I guess I'm starting to see a solution.

Here my second attempt:

class Chat implements WampServerInterface
{
    protected $conversation  = array();
    public function onSubscribe(ConnectionInterface $conn, $conversation_id){
        $conversation_id = (string) $conversation_id;
        if(!array_key_exists($conversation_id, $this->conversation)){
            $this->conversation[$conversation_id] = 1;
        }
        else{
            $this->conversation[$conversation_id]++;
        }
        echo "{$this->conversation[$conversation_id]}\n";
        echo "Client $conn->resourceId assigned to the conversation : {$conversation_id}\n";
    }
    public function onUnSubscribe(ConnectionInterface $conn, $conversation_id){
        // Foreach conversations or given conversation remove one client
        $this->conversation[$conversation_id]--;
        echo "$this->conversation[$conversation_id]\n";
        echo "Client $conn->resourceId left the conversation : $conversation_id\n";
    }
    public function onOpen(ConnectionInterface $conn){
        echo "New connection! ({$conn->resourceId})\n";
    }
    public function onClose(ConnectionInterface $conn){
        $this->onUnsubscribe($conn, $this->conversation);
        echo "Connection closed!\n";
    }
    public function onCall(ConnectionInterface $conn, $id, $fn, array $params){
    }
    public function onPublish(ConnectionInterface $conn, $conversation_id, $event, array $exclude, array $eligible){
        $conversation_id = (string) $conversation_id;
        $nb_clients = $this->conversation[$conversation_id]
        echo "$nb_clients User(s) in conversation";
        echo "Message sent to $conversation_id : $event";
        // ...
        $message = $event; 
        // Send data to conversation
        $this->conversation[$conversation_id]->broadcast($message);
    }
    public function onError(ConnectionInterface $conn, \Exception $e){
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

Any ideas if that would properly work? It actually seems to work but i'm still not sure if it is the best solution. I actually got inspired from Ratchet github.


Source: (StackOverflow)

How to bind ZeroMQ socket with Ratchet web-socket library to make real time application for php application?

I am just a beginner in this whole area involving websocket, Ratchet and ZeroMQ.

To my basic understanding:

websocket is something that helps to create open connection between server and client.

Ratchet is a PHP based library which uses PHP's core Socket functions to create a PHP socket framework allowing us to ease in PHP socket programming.

ZeroMQ is a socket library that helps non-ratchet application to (other PHP script) send the data over Ratchet Socket and web-socket.

I am following the tutorial found in ratchet about 'hello world' and 'pusher' but both of them seems to be incomplete and only teaches how to work with console only. I have also found ratchet-example in github but it is not properly documented. I was looking for a complete example (with a dedicated html page and javascript)

Below is the code I am working on: This is one of the method of the controller which I am making a Ajax request for. This method will create a new post (lets say). I want to update the list of post dynamically in multiple client's browser by broadcasting/pushing with the help of ZeroMq.

A method in a controller:

public function create_new_post(){
    // ------
    // code to create a new post.
    // -------

    // After creating a post
    $response = [
        'new_post_title'    => $title,
        'post_id'           => $id
    ];

    $context = new ZMQContext();
    $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
    $socket->connect("tcp://localhost:8000");
    $socket->send(json_encode($response));

}

Pusher File:

use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class Pusher implements WampServerInterface{

     public function onPostEntry($data){
         // Data that were sent by ZeroMQ through create_new_post() method
         $entry_data = json_decode($data);      

         // AND AFTER THIS, I DONT HAVE CLUE OF WHAT TO DO NEXT !!             

     }
}

Shell Script to run server:

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:8000'); 
$pull->on('message', array($pusher, 'onBidEntry'));

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

$loop->run();

Shell script only tells that it will serve in port 8080, however how would I mention my routes. Lets say I want the open connection in only the page 'mysite/allposts'. Also, what would be the script that I have to write in client side (a javascript file) and how to receive these new data by client side updating a particular DOM object.


Source: (StackOverflow)

Ratchet Session Data Syncronisation using memcache

I created a Ratchet Web Socket Server and tried to use SESSIONS.

In my php file on the HTTP-Webserver (Port 80) I set the session-data like this

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;

$memcache = new Memcache;
$memcache->connect('localhost', 11211);

$storage = new NativeSessionStorage(array(), new MemcacheSessionHandler($memcache));
$session = new Session($storage);
$session->start();

$session->set('uname', $uname);

and connected to the Ratchet Websocket Server with Javascript

var RatchetClient = {

    url: "ws://192.168.1.80:7070",

    ws: null,

    init: function() {

        var root = this;
        this.ws = new WebSocket(RatchetClient.url);

        this.ws.onopen = function(e) {
            console.log("Connection established!");
            root.onOpen();
        };

        this.ws.onmessage = function(evt) {
            console.log("Message Received : " + evt.data);
            var obj = JSON.parse(evt.data);
            root.onMessage(obj);
        };

        this.ws.onclose = function(CloseEvent) {
        };

        this.ws.onerror = function() {
        };
    },

    onMessage : function(obj) {    
    },

    onOpen : function() {        
    }
};

The Server script works like descripted here: http://socketo.me/docs/sessions

If the client sends a message I fetch the session-data

$memcache = new Memcache;
$memcache->connect('localhost', 11211);

$session = new SessionProvider(
    new MyServer()
  , new Handler\MemcacheSessionHandler($memcache)
);


$server = IoServer::factory(
    new HttpServer(
        new WsServer($session)
    )
  , 7070
);

$server->run();



class MyServer implements MessageComponentInterface {

    public function onMessage(ConnectionInterface $conn, $msg) {

        $name = $conn->Session->get("uname");

    }
}

It works. If i set the session-data before connecting to the websocket then the uname is fechable inside my socket server script.

Whenever I change the session-data via ajax or from another browser window then the session-data of my running client will not been syncronized.

That means if i change the uname or destroy the session the socket server doesn't recognize this. It seems to be the case that Ratchet reads the session-data once on connect and after that the session object is independent.

Can you confirm that behaviour? Or am I doing something wrong. I thought the goal of using memcache is to be able to access the same session-data from different connected clients.

If I do a reconnect to the websocket after changing the session-data then the data has been updated.


Source: (StackOverflow)

Creating/Managing private rooms using Ratchet?

I am making ios chat application. After doing study on needed technology and protocols, i decided to give a websockets try. For reasons our stack top is php based and i came to know about ratchet as websockets for PHP. I made simple chat server for ios front-end from reading documentation. Chat is working very fine and i am comfortable with it too. I wanted to know on how to create separate private chat rooms. Will different instance of socket event loop needed to run for separate rooms ?

  • The sample server i made is using single event loop for managing user connections and dispatching messages to different connection/user id's. I really tried to look out for creating private chat rooms but haven't found any information where i could be confident. Will i have to manage each connection/user id's virtually on this event loop, like deciding which users can chat to each other directly by controlling the dispatching of messages ? Or Is their really a separate way to do this ? This is the event loop sample as par documentation that i implemented:

       require dirname(__DIR__) . '/vendor/autoload.php';
    
       $server = IoServer::factory(
           new HttpServer(
               new WsServer(
                   new Chat()
               )
           ),
           8080
       );
    
       $server->run();
    

I want to tell that i am a ios/android developer and really no expert or have fluent knowledge on web frontend/backend technologies. I do web programming as a hobby and i did all search and research as much i could do hence please don't mind if my any questions sounds silly.

Thanks,


Source: (StackOverflow)

Ratchet PHP and long running tasks

I am using ratchet php. I am starting it like this:

$loop    = \React\EventLoop\Factory::create();
$webSock = new \React\Socket\Server($loop);

$webSock->listen($this->port, $this->host);

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

return $loop;

Now, in my onMessage() of my Pusherserver class (which implements MessageComponentInterface), I want to perform a long, blocking task. It will be an HTTP request which could take up to ten seconds to complete.

How do I make onMessage() free to handle other requests while the previous HTTP request is executing? I cannot use pthreads as I don't have access to change the php version that I am already given (which is thread safe).


Source: (StackOverflow)

How to send messages to particular users Ratchet PHP Websocket

I'm trying to build a system where user can subscribe to a category on establishing connection to websocket server and then he will start receiving updates for that category. So far, I have worked with Ratchet and I am able to send message to all the connected clients but the problem is I don't want to send message to all the clients I just want to send the message to the clients who have subscribed the the particular category in which the messages was sent.

PHP Code

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)
    {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        foreach ($this->clients as $client)
        {
            if($conn !== $client)
                $client->send($msg);
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

server.php

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

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

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

$server->run();
?>

Client side js code

<script type="text/javascript">
var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {
  console.log("Connection established!");
};

conn.onmessage = function(e) {
  console.log(e.data);
};
</script>

Source: (StackOverflow)

How to show connected user online using ratchet?

Can you please tell me how to show connected user online using ratchet? I mean I want to send some kind of userid to the server and broadcast this id to all other connected users showing that this userid is online.


Source: (StackOverflow)

PHP Ratchet Wamp Broadcast to subscribers on publish event

I am developing a web application where I need real time behavior for the following scenario,

Application will have two type of users Player and Spectator. Players can join an going game while Spectators can mere spectate.

A game will be initialized by an admin user.

A spectator is basically someone who can see the list of people who have joined a game. Of course this needs to be real-time meaning when a player disconnects or a new player joins a game spectator sees the real time list.

To summarize, consider the below example

Spectator_1 joins Clan_101 
Spectator_2 joins Clan_201

Player_1 joins Clan_101 // Need to broadcast this event to Spectator_1
Player_2 joins Clan_101 // Need to broadcast this event to Spectator_1
Player_1 disconnects Clan_101 // // Need to broadcast this event to Spectator_1

Player_11 joins Clan_201 // Need to broadcast this event to Spectator_2
Player_12 joins Clan_201 // // Need to broadcast this event to Spectator_2

Considering an on-going game as a topic/channel (Ratchet\Wamp\Topic), I need to broadcast to spectators on the following events player join and player left to the game/topic on which spectators have subscribed.

I am using Ratchet WebSockets for PHP on server side and autobahn js on client side

Below is the code. So far where I am able to send information to server(from client) when a player joins/disconnects a game. But How do I broadcast this information to spectators(client end) when a player joins or disconnects.

player.html

<script src="scripts/autobahn.js" type="text/javascript"></script>
<script src="scripts/jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
ab.connect(
    'ws://localhost:8080',
     function (session) {
         appSession = session;
         $('#btnJoinGame').on('click',function(){
         session.publish('joingame', ['data','GAME_ID']);
     });                   
 });
</script>

spectator.html

<script>
var conn = new ab.Session(
    'ws://localhost:8080', 
    function() {            
         conn.subscribe('spectator_GAME_ID', function(topic, data) {
            console.log(topic);
            console.log(data);
         });
     },
     function() {            
        console.warn('WebSocket connection closed');
     }    
 );  
 /* OR Using the legacy syntax */
 /*
     ab.connect(
         'ws://localhost:8080',
          function (session) {
              session.subscribe("t1011", function (topic, event) {
                  console.log(event);
              });
          }                       
      );
 */
</script>

Server.php

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

use Ratchet\Wamp\WampServerInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface as Conn;


class EventHandler implements WampServerInterface, MessageComponentInterface{
     public function __construct(React\EventLoop\StreamSelectLoop $loop){
        $this->loop = $loop;
     }
     public function onSubscribe(Conn $conn, $subscription, $params = array()){   
        $subscription->broadcast($this->data);
     }

     public function onPublish(Conn $conn, $topic, $params, array $exclude, array $eligible) {
        if($topic->getId() === 'joingame'){
            if(!isset($this->data[$params[1]])){
                $this->data[$params[1]] = array($params[0]);
            }else{
                array_push($this->data[$params[1]], $params[0]);
            }            
        }
        /** DOES'NT WORKS **/
        $newtopic = new Ratchet\Wamp\Topic('spectator_GAME_ID');
        $this->onSubscribe($conn,$newtopic);
    }
    /*Omitting other methods for brevity*/
}

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

$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(    
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                new EventHandler($loop) // This is my class. Pass in the loop!
            )
        )
    ),
    $webSock
);

$loop->run();

Source: (StackOverflow)

How do I install Ratchet WebSockets for PHP on MAMP or XAMPP?

I'm trying to integrate a real time chat into my php / backbone app and I thought I would use ratchet? What do I need to do to install Ratchet into MAMP or XAMPP? The only documentation provided on their website is to use CURL, but I don't know how to install the necessary resources for localhost, nor do I know where those resources need to be add to. Any advice would be appreciated.


Source: (StackOverflow)