I made the following class:
class Socket {
private $socket;
private $loop;
private $enviarMensagem;
function __construct(LoopInterface $loop, $enviarMensagem) {
$this->loop = $loop;
$this->enviarMensagem = $enviarMensagem;
$this->socket = stream_socket_client('tcp://172.20.50.222:4444');
$loop->addReadStream($this->socket, array($this, 'recebeMensagem'));
}
public function recebeMensagem() {
$server_response = fread($this->socket, 4096);
}
public function sendMessageToPainel($nomeContato, $idContato, $idMensagem, $tipoMensagem, $conteudoMensagem) {
$response = array(
'method' => 'onEnviarMensagem',
'params' => array(3,
'tempwictor',
5,
$nomeContato,
$idContato,
$idMensagem,
$tipoMensagem,
$conteudoMensagem,
1)
);
stream_socket_sendto($this->socket, json_encode($response) . "\r\n");
}
}
It works perfectly, I made a socket stream server that returns all the messages it receives for testing:
$server = stream_socket_server("tcp://0.0.0.0:4444", $errno, $errorMessage);
if ($server === false) {
die("Could not bind to socket: $errorMessage");
}
$client_socks = array();
$i = 0;
while (true) {
$read_socks = $client_socks;
$read_socks[] = $server;
if (!stream_select($read_socks, $write, $except, 300000)) {
die('something went wrong while selecting');
}
if (in_array($server, $read_socks)) {
$new_client = stream_socket_accept($server);
if ($new_client) {
echo '\nConnection accepted from ' . stream_socket_get_name($new_client, true);
$client_socks[] = $new_client;
echo "\nNow there are total " . count($client_socks) . " clients.n";
}
unset($read_socks[array_search($server, $read_socks)]);
}
foreach ($read_socks as $sock) {
$data = fread($sock, 1024);
if (!$data) {
unset($client_socks[array_search($sock, $client_socks)]);
@fclose($sock);
echo "\nA client disconnected. Now there are total " . count($client_socks) . " clients.n";
continue;
}
if(($i%3) == 0){
fwrite($sock, $data . "\r\n");
fwrite($sock, $data . "\r\n");
fwrite($sock, $data . "\r\n");
}
fwrite($sock, $data . "\r\n");
$i++;
}
}
But this server is only for testing, I need to communicate with a server that does not use socket stream, I can send, but the receipt is not possible, since the other server's communication is not stream.
The code for this server I do not have access to, but I have another application that communicates with it through the conventional socket.
I'm using the reactphp loop in an instagram api, I started using it just because of this api so I know very little about this tool, I wanted to continue with it since api uses it for almost everything, the only way it I found it was using the socket stream.
I found this link , I did some research and found that the ReadableResourceStream and WritableResourceStream does not work on windows, so I abort this possibility.