PHP : echo not working in infinite while loop - php

I want to show $input from the client using echo on the server side.
PHP Server:
<?php
$socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
$input = fread($conn, 1024);
echo $input;
fwrite($conn, 'Wait for a while... ' . $input);
fclose($conn);
}
fclose($socket);
}
fwrite() successfully writes $input to client but echo $input displaying nothing.

You should use flush():
<?php
$socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
$input = fread($conn, 1024);
echo $input;
ob_flush();
flush();
fwrite($conn, 'Wait for a while... ' . $input);
fclose($conn);
}
fclose($socket);
}

Related

PHP array mysterious behavior as "Undefined index"

I am practicing socket programming using stream methods in PHP.
I am using PHP 7.3.11.
I found very unexpected error message which says "undefined index " error where
Here is my server side code
<?php
error_reporting(E_ALL);
/* allow the script to hang around waiting for connection.*/
set_time_limit(0);
$address = '127.0.0.1';
$port = 9016;
$server = stream_socket_server($address .":". $port, $errno, $errorMessage);
$req = array( "R004"=>"R004 exist"
, "R001" => "R001 Ruccess"
, "R002"=>"R002Rcontinue"
, "R003"=>"R003 lRquit"
, "R005"=>"R005 hello");
$res = array("TT","SOO1", "S002", "S003");
if ($server === false)
{
throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
}
echo json_encode($req);
while($socket = stream_socket_accept($server)){
$rand = rand(1,3);
$peer = stream_socket_get_name($socket, true);
$pkt = stream_socket_recvfrom($socket, 1500, 0,$peer);
if( !empty($pkt)){
$pkt = trim(preg_replace('/\s+/','',$pkt));
echo "pkt[{$pkt}]";
echo "EXITS:".array_key_exists($pkt, $req)."\n";
echo "pkt[{$pkt}]".PHP_EOL;
echo $req[$pkt].PHP_EOL;
stream_socket_sendto($socket, $res[$rand], 0, $peer);
}
fclose($socket);
usleep(1000);
}
stream_socket_shutdown($server, \STREAM_SHUT_RDWR);
and here is my client side code
error_reporting(E_ALL);
set_time_limit(0);
$address = '127.0.0.1';
$port = 9016;
$local = "tcp://{$address}:{$port}";
$socket = stream_socket_client($local, $errno, $errstr, 30);
$c_res = array("S001" => "Success", "S002" => "continue", "S003" => "quit");
$c_req = array("ROO3", "R005", "R002", "R001", "R004");
while ($socket = stream_socket_client($local, $errno, $errstr, 30)) {
$rand = rand(1, 4);
// echo "SEND[$c_req[$rand]]" . PHP_EOL;
$sent = stream_socket_sendto($socket, $c_req[$rand] . PHP_EOL);
if ($sent > 0) {
usleep(1000);
$s_res = stream_socket_recvfrom($socket, 1500, 0, $peer);
// $s_res = fread($socket, 4096);
$s_res = trim(preg_replace('/\s+/', '', $s_res));
echo "c_res[{$s_res}]";
echo "EXITS:" . array_key_exists($s_res, $c_res) . "\n";
echo "c_res[{$s_res}]" . PHP_EOL;
echo $c_res[$s_res] . PHP_EOL;
}
}
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
when I ran this code both server and client ( server runs first and thereafter does client)
I found this kind of error message
PHP Notice: Undefined index: SOO1 in E:\xampp\htdocs\mave_gen\www\adm\client.php on line 29
I do not understand this error message at all because all other references prints out OK except S001.
Obviously, there is S001 is defined in the code.
Do I miss something here ?
Thank you in advance.
The line SOO1 should be S001 in $res = array("TT","SOO1", "S002", "S003"); in the server side code. You have entered letter "O" in SOO1 but it should be "0" (zero) according to the rest of your code.
And in the client side code modify the following line of code
if ($sent > 0) {
usleep(1000);
$s_res = stream_socket_recvfrom($socket, 1500, 0, $peer);
// $s_res = fread($socket, 4096);
$s_res = trim(preg_replace('/\s+/', '', $s_res));
echo "c_res[{$s_res}]";
echo "EXITS:" . array_key_exists($s_res, $c_res) . "\n";
echo "c_res[{$s_res}]" . PHP_EOL;
echo $c_res[$s_res] . PHP_EOL;
}
to the following line
if ($sent > 0) {
usleep(1000);
$s_res = stream_socket_recvfrom($socket, 1500, 0, $peer);
if(!empty($s_res))
{
// $s_res = fread($socket, 4096);
$s_res = trim(preg_replace('/\s+/', '', $s_res));
echo "c_res[{$s_res}]";
echo "EXITS:" . array_key_exists($s_res, $c_res) . "\n";
echo "c_res[{$s_res}]" . PHP_EOL;
echo $c_res[$s_res] . PHP_EOL;
}
}
After these changes it should work.

socket_select() not a valid socket

I got this error:
Warning: socket_select(): supplied argument is not a valid Socket resource in /volume1/web/is/xxxx/listen-new.php on line 12
PHP Warning: socket_select(): supplied argument is not a valid Socket resource in /volume1/web/is/xxxx/listen-new.php on line 12
this my snippet code
My code is:
$port = $this->port;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, 0, $port);
socket_listen($sock);
$this->clients[] = $sock;
$data = array();
while (true) {
$read = $this->clients;
$write = array(); //NULL
$except = array();//NULL
$sckt = socket_select($read, $write, $except, 0);
if($sckt === false){
echo "socket_select() failed, reason: " .
socket_strerror(socket_last_error()) . "\n";
}
elseif($sckt > 0) {
if (in_array($sock, $read)) {
$this->clients[] = $newsock = socket_accept($sock);
//var_dump($this->gps);
socket_write($newsock, "Connected\n");
//var_dump($this->gps);
/**try{
socket_getpeername($newsock, $ip); //error
echo "New client connected: {$ip}\n";
}
catch(Exception $e){
echo "error : $e->getMessage()\n";
}**/
$key = array_search($sock, $read);
unset($read[$key]);
}
foreach ($read as $read_sock) {
$data = #socket_read($read_sock, 2048);
if ($data === false) {
$gpsdisc = array_search($read_sock, array_column($this->gps, 'pid'));
$key = array_search($read_sock, $this->clients);
unset($this->clients[$key]);
unset($this->gps[$gpsdisc]);
echo "client disconnected.\n";
continue;
}
else{
$data = trim($data);
if (!empty($data)) {
var_dump($data);
$buf = bin2hex($data);
$start = substr($buf, 0,4);
if($start=="7878"){
$protocol = substr($buf, 6,2);
if($protocol=="01"){
$imei = substr($buf, 8,16);
$cariGPS = $this->cariGPS($imei);
if($cariGPS!=NULL){
$this->setGPS($imei,$read_sock,$cariGPS);
$reply = $this->authLogin($data);
$rep = hex2bin("$reply");
socket_write($read_sock, $rep, strlen($rep));
}
else
echo "$imei salah";
}
elseif($protocol=="15"){
//echo "$buf\n";
$this->reply($data);
}
elseif($protocol=="12"){
$hex12 = bin2hex($data);
//echo "$hex12\n";
}
else{
$hex12 = bin2hex($data);
echo "$hex12\n";
}
echo "$protocol\n";
}
else{
if($data=="where"){
//echo $data."\n";
$this->where($this->gps);
}
elseif($data=="quit"){
$gpsdisc = array_search($read_sock, array_column($this->gps, 'pid'));
unset($this->gps[$gpsdisc]);
socket_close($read_sock);
$key = array_search($read_sock, $this->clients);
unset($this->clients[$key]);
}
else{
echo "command not found\n";
}
}
}
}
}
}
}
socket_close($sock);
PS I also had to change $write = null and $except = null
Are there any solution for this?
It looks like you supplied only the server code but omitted the client code. Can you post the client code please? I guess the problem is there. With my test client (fyi I used socket_create) I cannot reproduce the problem you are reporting.
Also mine is php7 (if you are curious).
This may have some hints for you: Socket_read() says "not a valid resource"

fsockopen return value false or true

I have the following code:
$check1 = fsockopen("111.222.333.444","8080");
if ($check1) {
echo ("true");
$close = fclose($check1);
}
else
echo ("false");
How do I get it back to me this value true and false in a string?
Example:
if($check1 == "false") {
// Conecct SSH
if($check1 == "true") {
// Not connect SSH
You need more parameters:
$check1 = fsockopen($host, $port, $errno, $errstr);
if (!$check1) { // $check1==false
echo $errno . ' ' . $errstr
} else { // $check1==true
//Your code
}

how to accept multiple connection to the device

I am creating a socket script that will listen to our 3 devices.and the device is setup in one server ip and one port only.
$file = fopen('txt.log','a+');
$server = stream_socket_server('tcp://'.$ipserver.':'.$port, $errno, $errorMessage);
if(!$server) {
echo "$errorMessage ($errno)<br />\n";
}
else{
while($client = #stream_socket_accept($server,$timeout)) {
stream_copy_to_stream($client, $file);
fclose($file);
fclose($client);
}
}
but the problem is that if one device is connected,the two devices cannot connect anymore.I appreciate some one can help me how to get this work.or give me some idea
Thank you in advance.
$file = fopen('txt.log', 'a+');
$server = stream_socket_server("tcp://$ipserver:$port", $errno, $errorMessage);
if (!$server)
echo "$errorMessage ($errno)<br />\n";
else
{
$s = array($server);
$t = $timeout == -1 ? NULL : $timeout;
while ($r = $s and stream_select($r, $n=NULL, $n=NULL, $t))
foreach ($r as $stream)
if ($stream == $server) // new client
$s[] = stream_socket_accept($server, -1);
else
if (!fputs($file, fgets($stream)))
{
fclose($stream);
array_splice($s, array_search($stream, $s), 1);
}
}

How to print the last string from socket

I'm trying to print the last string from server respone. I'm write the following:
$fp = fsockopen("smtp.mail.ru", 25);
// There is fputs functions
echo fgets($fp);// This is print the first string
But I want to print the last string of the server's response. Is it possible to do?
You can put the strings into array of stings, then print the last string:
<?php
$cntr = 0;
$strarray = [];
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp)
{
echo "$errstr ($errno)<br />\n";
}
else
{
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp))
{
$strarray[$cntr] = fgets($fp);
$cntr = $cntr + 1;
}
fclose($fp);
}
//Now, print the last string in the array:
echo end($strarray);
?>

Categories