Search code examples
phpnode.jssocketssocket.io

PHP sending message to Node / Socket.IO server


I'm not too sure if I'm going about this in the right way. I want to stick with my Socket.IO server, and do not want to create a separate HTTP server within node. With this, can I create a PHP client that can send data (e.g.: player buys item from online shop) to the node Socket.IO server directly?

I've started with this:

<?php

class communicator {
   public function connect($address, $port){
      $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

      if($socket){
          try {
              socket_connect($socket, $address, $port);
          } catch(Exception $e){
              throw new Exception($e->getMessage());
          }
      }else{
          throw new Exception('Could not create socket.');
      }
}

?>

The socket seems to connect just fine to the node server, but how can I start receiving data directly from the PHP client?

E.g.: Say I use socket_write to send a message to the server. How do I get that through Socket.IO?

Hope my question makes sense!


Solution

  • im using http://elephant.io/ for comunication between php and socket.io, i have only problems with the time to stablish connection, 3 or 4 seconds to complete sending data.

    <?php
    
    require __DIR__ . '/ElephantIO/Client.php';
    use ElephantIO\Client as ElephantIOClient;
    
    $elephant = new ElephantIOClient('http://localhost:8080', 'socket.io', 1, false, true, true);
    
    $elephant->init();
    $elephant->emit('message', 'foo');
    $elephant->close();