Reputation: 9072
I'm running a ratchet websocket server. Due to some complicated circumstances I need to be able to talk to this websocket server via my PHP Server in realtime not Javascript to be able to send it information that will then be passed on later to any clients connected to it.
I did some looking around on stackoverflow but everything is about how to create a websocket server with PHP which is not what I'm looking for.
Below is a visual of what I'm trying to achieve.
The key here is how to connect to a Websocket server like ratchet using PHP?
Things I have tried/considered:
I've considered using the serialization approach. This would be serializing in the database and unserializing. I'm not sure if this is better than this approach, please advise.
This is where I started : Ratchet Store Connection of User & Send Message Outside of Server Instance
Upvotes: 2
Views: 2159
Reputation: 3826
I would suggest using REST as API layer for communication between your Symfony app and Ratchet app. Because it doesn't make much sense to use Websocket from your Symfony app. Websockets are used for bidirectional real-time communication, whereas you only need to send a piece of data from your Symfony app. For this purpose, HTTP REST API would be more convenient. To wrap it up, in your Ratchet app you use 2 servers (Ratchet allows creating as many servers as you want within a single app): web-socket server and http-server. In your Symfony app, you send traditional HTTP requests to your Ratchet server.
You can create multiple Ratchet servers in a single app like so:
// 1. Create the event loop
$loop = React\EventLoop\Factory::create();
// 2. Create servers
// websocket
$webSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer( $wsConnectionsHandler )
),
$webSock
);
$webSock->listen($portWS, '0.0.0.0');
// http
$httpSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
$HTTPConnectionsHandler
),
$httpSock
);
$httpSock->listen($portHTTP, '0.0.0.0');
// 3. Run the loop
$loop->run();
How do I pass the information from the http server to the websocket server?
React/Ratchet app is an event-driven app, like a typical NodeJS app. So the best way for the components of the app to communicate with each other is to dispatch/subscribe events. For example, you create $eventDispatcher
object, pass it to every component (http-handler & ws-handler), and then use $eventDispatcher->subscibe(eventName, func)
and $eventDispatcher->emit(eventName, data)
to subscribe to events and dispatch them accordingly.
If you are not convinced, then you need to use a Websocket Client library to connect to Websocket server. There are a few of them, just google it. I personally never used a PHP websocket-client library, so I can't recommend any.
Upvotes: 2