Ratchet: how to trigger onMessage function from server-side ?

in my project , i want to send data to some clients automatically , without receiving any request from clients.but i cant access to clients from out side of MessageComponentInterface class object. i prefer to tell to MessageComponentInterface class ; send to alive clients a message. so i need to trigger onMessage function from server-side , how can i do it ? here is my WebSocketCon class :

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

class WebSocketCon implements MessageComponentInterface {
    protected $clients;
    public $users;
	
    public function __construct() {
        $this->clients = new \SplObjectStorage; 
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg);
        if($data->command=="subscribe"){
            $this->users[(int)$data->uid] = $from;
            echo "New subscribe! ({$data->uid})\n";
        }
    }

    public function sendMessageToAll($msg){
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send($msg);
            }
        }
    }
	
    public function sendMessageTo($idusers,$msg){
        foreach ($idusers as $idu) {
            $idu = (int) $idu;
            if(array_key_exists($idu,$this->users)){
                $this->users[$idu]->send($msg);
            }
        }
    }
	
    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn); 
            if (($key = array_search($conn, $this->users)) !== false) {
                unset($this->users[$key]);
            }
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

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

        $conn->close();
    }
}

and here is my cmd.php :

<?php
require 'vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer; 
require 'classes/WebSocketCon.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new WebSocketCon()
        )
    ),
    8081
);

$server->run();
?>

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 25 (3 by maintainers)

Most upvoted comments

Hello! You should to look at the ZMQ (Push integration) module. It described on socketo.me in the “Push integration” tab. 😃

@halfer
I solved the problem, never deploy the sockets to windows. My solution is to install ubuntu 16.04 and configure and work and forget about the window

Update your cmd.php to give access to yourWebSocketCon class:

<?php
require 'vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer; 
require 'classes/WebSocketCon.php';

$app = new WebSocketCon();

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            $app
        )
    ),
    8081
);

// Somewhere else:
$app->sendMessageToAll('Hi everyone!');

$server->run();

If you’re looking for a full blown WebSocket client see Ratchet’s Pawl.

I seem to have problems that are similar to the ones mentioned in this thread.

I followed the push tutorial and changed nothing to the code.

The client side is working fine (thus subscribing and unsubscribing etc works) but whenever I try to execute the file from the step Editing your blog submission it keeps loading for a long while and eventually gives me the following error message (in Chrome) ERR_CONNECTION_RESET

When I do the following var_dump:

$context = new ZMQContext();

$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");

var_dump($socket); exit;

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

It returns the following: object(ZMQSocket)#2 (0) { }

(but after the first time it will return the same error as above ERR_CONNECTION_RESET)

I tried disabling the firewall. But that did not make any difference.

Everything else seems to work just fine. But just broadcasting from the server does not work.

It might be important to note that this is all done on a xampp server running on Windows

@rfrancois: For web sockets I just use the raw JS class on the browser side, and textalk/websocket on the PHP side (the latter should not cause any different behaviour, all WS libraries should work about the same).

In the client code in that tutorial, I can’t see any acknowledgement of the browser to server connection. I do this:

    var
        isSecure = window.location.protocol === 'https:',
        protocol = isSecure ? 'wss://' : 'ws://',
        address = protocol + window.location.host;

    console.log("Attempting a WebSocket connection on `" + address + "`");
    ws = new WebSocket(address);

    ws.onopen = function () {
        console.log('WS connection opened');
    };

    ws.onmessage = function (e) {
        // Handle an incoming message here
    };

    ws.onclose = function (e) {
    }

Try that and see if you get a browser to server connection?

If you think that SELinux is to blame, try a version of Linux without it (either on a separate computer or a virtual machine).

I tested it, Push message it well sent and received by the push server:

Arguments received by onBlogEntry method:

array(1) {
  [0]=>
  string(51) "{"category":"sm","title":"saleh","when":1508784615}"
}

It looks like the problem is after, when broadcasting this message to websocket clients.

Are you just looking for a Web Socket client you can use programmatically? I use textalk/websocket for this.