Skip to content

Instantly share code, notes, and snippets.

@sshilko
Created Mar 27, 2016
Embed
What would you like to do?
<?php
error_reporting(E_ALL);
send_message('127.0.0.1','8000', getmypid() . ' Message to send...');
function send_message($ipServer,$portServer,$message)
{
$fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
stream_set_blocking($fp, false);
if (1) {
while(1) {
$wr = array($fp);
$rr = array($fp);
$nl = null;
if ($ss = stream_select($nl, $wr, $nl, 1, 0) > 0) {
echo 'SS result=';
var_dump($ss);
$written = fwrite($fp, "$message" . time() . "\n");
echo 'Written result:';
var_dump($written);
if ($written === false) {
echo "FAILED TO WRITE";
sleep(1);
}
if ($written === 0) {
$info = stream_get_meta_data($fp);
print_r($info);
if (feof($fp)) {
echo 'FEOF detected';
}
sleep(1);
}
echo 'Written=' . $written . "\n";
sleep(1);
} else {
echo 'cant select to write';
}
}
}
}
<?php
$socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);
echo "Dispatching...\n";
pcntl_signal_dispatch();
register_shutdown_function(function($s) {
echo 'Doing shutdown';
@fclose($s);
}, $socket);
while(1) {
$conn = @stream_socket_accept($socket, 10);
if ($conn) {
while($data = fread($conn, 1024)) {
if ($data) {
echo "RCV: " . $data;
}
}
@fclose($conn);
} else {
break;
}
}
@fclose($socket);
@sshilko
Copy link
Author

sshilko commented Mar 27, 2016

http://php.net/manual/en/function.fwrite.php

function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}

Example seems to create** infinite LOOP** because FALSE is never returned, this is also mentioned in comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment