I'm working on an object-oriented application in PHP that connects to a remote server to read and send data. To do this, I am using fsockopen()
, fgets()
to read, fwrite()
to write and fclose()
.
I simplified it to just the neccessary code:
<?php
namespace myApplication;
class client {
protected $socket;
public $connected = false;
public function connect(string $host, int $port) : bool {
if (($this->socket = fsockopen($host, $port, $errno, $errstr, 15)) == false) {
return false; //or error handling
}
$this->connected = true;
return true;
}
public function disconnect() {
if ($this->connected) {
@fclose($this->socket);
$this->connected = false;
}
}
public function read() : ?string {
if ($this->connected === false) {
/*
throw error
*/
}
if (($data = fgets($this->socket)) !== false) {
return $data;
}
else {
/*
error handling
*/
}
}
public function write($write_data) : bool {
if ($this->connected === false) {
/*
throw error
*/
}
$write_data .= "\r\n"; //carriage return, newline
if (fwrite($this->socket, $write_data, strlen($write_data)) != false) {
return true;
}
else {
/*
error handling
*/
return false;
}
}
}
First it seems like everything works as expected. The client connects to the server, it successfully retrieves the first greeting line sent by the server and as fwrite()
is called it returns that it successfully wrote all bytes. (PHP Documentation says the function's return value is the number of written bytes.) So all this seems to work just fine.
But the server nevers gets data from the client. I tested the client with a little bare-bone PHP socket server that I wrote for debugging purposes, but it also does not retrieve any data from the client.
I don't know why this is the case. The connection is being established successfully and as mentioned the client can retrieve data from the server. But for any reason, fwrite()
does not successfully sent the data.
There are no error or warning messages. Log level E_ALL
.
php --version
output: PHP 7.3.19-1~deb10u1For further information please ask here, I will be active and answering questions.
It appears that in this case fwrite
only writes to a Buffer instead of directly sending the data.
To force the sending fflush
can be used.