I am building a multi-threaded PHP CLI application that speaks with a server via sockets. The intention is for the application to only create one connection with the server (via a separate class) and then allow the child threads to use the established socket object. The following code fails:
<?php
/**
* Test child class
**/
class test extends Thread {
private $server;
public function __construct( &$server ) {
$this->server = $server;
}
public function run() {
echo $this->server->request( 'INFO 1-10' );
}
}
/**
* Socket class
**/
class socket {
private $socket;
public function __construct( $host, $port ) {
$this->socket = fsockopen( $host, $port, $errno, $errstr, 10 );
}
public function request( $out ) {
fwrite( $this->socket, $out . "\r\n" );
return fgets( $this->socket );
}
}
/**
* main class
**/
class main {
private $server;
public function __construct() {
$this->server = new socket( '192.168.1.141', 5250 );
}
public function main() {
$test = new test( $this->server );
$test->start();
}
}
$main = new main();
$main->main();
?>
The error message is:
PHP Warning: fwrite() expects parameter 1 to be resource, integer given in /test_stackoverflow/test.sh on line 35
PHP Stack trace:
PHP 1. {main}() /test_stackoverflow/test.sh:0
PHP 2. socket->request() /test_stackoverflow/test.sh:17
PHP 3. fwrite() /test_stackoverflow/test.sh:35
PHP Warning: fgets() expects parameter 1 to be resource, integer given in /test_stackoverflow/test.sh on line 36
PHP Stack trace:
PHP 1. {main}() /test_stackoverflow/test.sh:0
PHP 2. socket->request() /test_stackoverflow/test.sh:17
PHP 3. fgets() /test_stackoverflow/test.sh:36
If I remove the Thread aspect, and use the following code:
<?php
/**
* Test child class
**/
class test {
private $server;
public function __construct( &$server ) {
$this->server = $server;
}
public function run() {
echo $this->server->request( 'INFO 1-10' );
}
}
/**
* Socket class
**/
class socket {
private $socket;
public function __construct( $host, $port ) {
$this->socket = fsockopen( $host, $port, $errno, $errstr, 10 );
}
public function request( $out ) {
fwrite( $this->socket, $out . "\r\n" );
return fgets( $this->socket );
}
}
/**
* main class
**/
class main {
private $server;
public function __construct() {
$this->server = new socket( '192.168.1.141', 5250 );
}
public function main() {
$test = new test( $this->server );
$test->run();
}
}
$main = new main();
$main->main();
?>
This code runs successfully.
It appears that passing the $server object (socket class) by reference to a class that extends Thread causes the issue.
I was wondering if there was a way to accomplish my original goal of building a multi-threaded PHP CLI application that speaks with a server via a single sockets connection.
Thanks for your assistance!
The final application will be much more robust, allowing threads to be spawned dynamically. The example I provided above is to display the root issue, and nothing else.