Benjamin Tamasi
Benjamin Tamasi

Reputation: 712

PHP WebSocket Async task

I have the following scenario: I have a WebSocket running with Ratchet (PHP WebSocket) I use the onMessage() callback function to handle incomming data and respond accordingly. If I get the 'start-broadcast' message via the WebSocket I have to start a loop which will send out a broadcast message to all connected clients on the WebSocket every 0.2 sec. So I need to make a loop which can do this, but I can't put it into the onMessage() function, as this will block, and I won't be able to receive any more messages via the WS. If I get the 'stop-broadcast' message via the WebSocket I have to stop the broadcast loop.

So basically I need a way to start and stop this loop, and have this loop running parallel to the WebSocket loop so it doesn't block up.

Problems: The Socket->send() method I'm pretty sure is not thread-safe, so I need to make sure that the WS loop and my broadcast loop are not trying to send a message at the same time.

Possible approaches I have considered:

My question is, which approach should I take, and are there any examples or tutorials for the suggested approach?

Upvotes: 0

Views: 1348

Answers (1)

Maxim Tkach
Maxim Tkach

Reputation: 1697

If I get you right:

  • You get in a web-socket - command "start"
  • After receiving the request, you want to start broadcasting with 0.2 seconds interval
  • If you will come - command "stop", you need to stop broadcasting

Maybe I misunderstood the problem, but it's a bad idea, getting client requests start and stop brodcasting (what if everyone will send a "start command"?)

In general, I would recommend using ZMQ. This is the most scalable solution. (It is best to separate the services)

  • You start the server.
  • Waiting for commands from ZMQ, that you need to start broadcasting.
  • Once you get a command of ZMQ, create a timer with 0.2 second intervals and broadcasts
  • As soon as you get "command" stop in ZMQ - kill the timer.

OR

  • Your start the server ZMQ PUB and start brodcasting
  • Yout start web-socket
  • You give command start and start receive ZMQ SUB messages
  • You give command stop and stop receive ZMQ SUB messages

If you want a pub/sub service. Then simply create a Timer and have a list of who to broadcast. Client send "subscribe", and receive messages. Good idea use Redis for storing data between processes (WebSocket - ZMQ)

You need read ZMQ PHP DOC, before using ZMQ and see reactphp/zmq lib

Upvotes: 1

Related Questions