Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 350
Justin Avatar asked Feb 17 '14 09:02

Justin


People also ask

Can I use Socket.IO with PHP?

For 'long-lived connection' , you can use Ratchet for PHP. It's a library built based on Stream Socket functions that PHP has supported since PHP 5. For client side, you need to use WebSocket that HTML5 supported instead of Socket.io (since you know, socket.io only works with node. js).

Can you use Socket.IO with express?

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.

Does Socket.IO use polling?

js) and the Socket.IO client (browser, Node. js, or another programming language) is established with a WebSocket connection whenever possible, and will use HTTP long-polling as fallback.


2 Answers

I searched for this quite a bit and finally found a relatively simple solution.

This doesn't require any additional PHP libraries - it just uses sockets.

Instead of trying to connect to the websocket interface like so many other solutions, just connect to the node.js server and use .on('data') to receive the message.

Then, socket.io can forward it along to clients.

Detect a connection from your PHP server in Node.js like this:

//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.on("connection", function(s) {
    //If connection is from our server (localhost)
    if(s.remoteAddress == "::ffff:127.0.0.1") {
        s.on('data', function(buf) {
            var js = JSON.parse(buf);
            io.emit(js.msg,js.data); //Send the msg to socket.io clients
        });
    }
});

Here's the incredibly simple php code - I wrapped it in a function - you may come up with something better.

Note that 8080 is the port to my Node.js server - you may want to change.

function sio_message($message, $data) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, '127.0.0.1', 8080);
    if(!$result) {
        die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
    }
    $bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
    socket_close($socket);
}

You can use it like this:

sio_message("chat message","Hello from PHP!");

You can also send arrays which are converted to json and passed along to clients.

sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));

This is a useful way to "trust" that your clients are getting legitimate messages from the server.

You can also have PHP pass along database updates without having hundreds of clients query the database.

I wish I'd found this sooner - hope this helps! 😉

Late edit: Not sure if this is a requirement, but I added this to my http.conf (Apache config):

I figured I'd put the code here in case it helps anyone.

In httpd.conf I added the following code:

RewriteEngine On
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule .* ws://localhost:8080%{REQUEST_URI} [P]

ProxyRequests Off
ProxyPass        /socket.io http://localhost:8080/socket.io retry=0
ProxyPassReverse /socket.io http://localhost:8080/socket.io retry=0

ProxyPass "/node" "http://localhost:8080/"
like image 179
user1274820 Avatar answered Sep 25 '22 12:09

user1274820


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();
like image 29
Thomas Anderson Avatar answered Sep 25 '22 12:09

Thomas Anderson