PHP socket programming read after write blocking

Server server-side code.:
<?php
set_time_limit(0);
 
$host = "127.0.0.1";
$port = 12345;
 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create	socket\n"); // Create a Socket
 
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //The binding of Socket to port
 
$result = socket_listen($socket) or die("Could not set up socket listener\n"); // Start listening.
 
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // Communication processing

//If replaced by circular receiving data, the client will always wait for receiving state
$input = socket_read($spawn, 1024) or die("Could not read data\n");
/* 
while (( $data = socket_read($spawn, 1024)) != false) 
	$input .= $data;
*/ 

echo 'input:', strlen($input), "\n";
 
$output = date("Y-m-d H:i:s"). "\n"; //Processing client input and returns the result
 
echo "output:", $output, "\n";
 
//	Data transmission to the client to return results
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");	
 
// Close sockets
socket_close($spawn);
socket_close($socket);


Client end, the code as follows:
<?php

set_time_limit(0);
 
$host = "127.0.0.1";
$port = 12345;
 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create	socket\n"); // Create a Socket
 
$connection = socket_connect($socket, $host, $port) or die("Could not connet server\n");    //  Connect
 
socket_write($socket, "time") or die("Write failed\n"); // The data message is sent to the server

echo 'wait for data';

while (($buffer = socket_read($socket, 1024))!=false) {
    echo("Data sent was: time\nResponse was:" . $buffer . "\n");
}
 
socket_close($socket);

If the server end of the client read operation for circular internal read, then client would have been in a state of wait data.
Server is there a way to end the cycle time for the case, read data written to the client

Started by Cheryl at February 03, 2016 - 3:53 AM

You this cycle is not wrong, but a data transmission is complete to close the socket connection, no cycle of necessity.

Posted by Jeremiah at October 27, 2016 - 11:04 PM

<?php
set_time_limit(0);
 
$host = "127.0.0.1";
$port = 12345;
 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create	socket\n"); // Create a Socket
 
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //The binding of Socket to port
 
$result = socket_listen($socket) or die("Could not set up socket listener\n"); // Start listening.
 
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // Communication processing

//If replaced by circular receiving data, the client will always wait for receiving state
$input = socket_read($spawn, 1024) or die("Could not read data\n");
 
while (( $data = socket_read($spawn, 1024)) != false) 
{	$input .= $data;


echo 'input:', strlen($input), "\n";
 
$output = date("Y-m-d H:i:s"). "\n"; //Processing client input and returns the result
 
echo "output:", $output, "\n";
 
//	Data transmission to the client to return results
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");	
 }
// Close sockets
socket_close($spawn);
socket_close($socket);

Posted by Marcus at November 10, 2016 - 11:16 PM

<?php
set_time_limit(0);
 
$host = "127.0.0.1";
$port = 12345;
 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create	socket\n"); // Create a Socket
 
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //The binding of Socket to port
 
$result = socket_listen($socket) or die("Could not set up socket listener\n"); // Start listening.
 
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // Communication processing

//If replaced by circular receiving data, the client will always wait for receiving state
$input = socket_read($spawn, 1024) or die("Could not read data\n");
 
while (( $input = socket_read($spawn, 1024)) != false) 
{
	


echo 'input:', strlen($input), "\n";
 
$output = date("Y-m-d H:i:s"). "\n"; //Processing client input and returns the result
 
echo "output:", $output, "\n";
 
//	Data transmission to the client to return results
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");	
}
// Close sockets
socket_close($spawn);
socket_close($socket);

Posted by Marcus at November 19, 2016 - 11:31 PM

The response to 2013-09-25 10:14:45 was removed by the administrator

Posted by Baron at November 20, 2016 - 11:53 PM

This is just a demo, the actual situation, the client sends the data is not long, so only be received

Posted by Cheryl at November 22, 2016 - 12:42 AM

Read cycle which really should not use the PHP_NORMAL_READ option
Remove the PHP_NORMAL_READ option will not solve the problem, a solution to you

Posted by Cheryl at December 03, 2016 - 1:09 AM

while (true) {
    $msg = socket_accept ($socket);               // To accept a SOCKET
    if (!$msg) {
        echo "socket_accept() failed:".socket_strerror ($msg)."\n";
        break;
    }
    while (true) {
        $command = strtoupper (trim (socket_read ($msg, 1024))); //Waiting for client data
        if (!$command) break;
        //Correlation processing, such as direct echo
        socket_write ($msg, $command, strlen ($command));
    }
    socket_close ($msg);
    if ($command == "QUIT") //If the received communication end
        break;
}
socket_close ($socket);                   // Close SOCKET

Posted by Doris at December 15, 2016 - 2:00 AM

I use the stream function realization.
<?php

/*
 * Do not use Apache, CLI mode
 * The command receiver
 * A single user, single connection
 */

/**
 * The command receiver Messenger
 * Single thread
 */
class SocketServer {

    protected $ip;
    protected $port;
    protected $webSocket;
    protected $users;
    protected $userIndex = 0;
    protected $message;

    public function __construct($ip = "127.0.0.1", $port = 12345) {
        $this->ip = $ip;
        $this->port = $port;
        //
        self::init();
        //
        $this->createServer();
        $this->log('listenning user...');
        $this->listenningUser();
    }

    protected function createServer() {
        $errno;
        $errstr;
        $this->webSocket = stream_socket_server("tcp://" . $this->ip . ':' . $this->port, $errno, $errstr);
        if (!$this->webSocket) {
            self::log("$errstr ($errno)");
            exit();
        }
        $this->log('server ok .');
    }

    protected function listenningUser() {
        while (true) {
            $this->userIndex++;
            $user = $this->users[$this->userIndex] = stream_socket_accept($this->webSocket, 9999999999);
            //
            if (is_resource($this->users[$this->userIndex - 1])) {
                $u = $this->users[$this->userIndex - 1];
                $u->close();
                $u = NULL;
                unset($this->users[$this->userIndex - 1]);
            }
            //
            $this->log('Even into the new user');
            $this->listenningMessage();
        }
    }

    protected function listenningMessage() {
        while (is_resource($this->users[$this->userIndex])) {
            $this->message = stream_socket_recvfrom($this->users[$this->userIndex], 10270000);
            if (!$this->message) {
                $this->closeUser();
                break;
            }
            $this->messageOperate();
        }
    }

    function messageOperate() {
        $this->log("Received news:");
        $this->log($this->message);
        //mb_strstr($haystack, $needle, $before_needle, $encoding)
        $this->sendMessage('done');
    }

    function sendMessage($msg) {
        if($msg===''){
            return -1;
        }
        return stream_socket_sendto($this->users[$this->userIndex], $msg);
    }

    public function closeUser() {
        if (!is_resource($this->users[$this->userIndex]))
            return FALSE;
        @stream_socket_shutdown($this->users[$this->userIndex], STREAM_SHUT_RDWR);
        @fclose($this->users[$this->userIndex]);
        $this->log("The user is disconnected.");
        return TRUE;
    }

    public function shutdown() {
        stream_socket_shutdown($this->webSocket, STREAM_SHUT_RDWR);
        fclose($this->webSocket);
    }

    protected static function init() {
        error_reporting(E_ALL ^ E_NOTICE);
        set_time_limit(0);
        ob_implicit_flush();
        date_default_timezone_set('Asia/Shanghai');
        ignore_user_abort(TRUE);
        mb_internal_encoding('gbk');
    }

    protected static function log($message) {
        echo "\r\n" . $message . "\r\n";
    }

}




$server = new SocketServer();




<?php

/*
 * Do not use Apache, CLI mode
 * The client
 */

class SocketClient {

    protected $client;
    protected $message;

    public function __construct($domain,$port) {
        $this->init();
        $this->client = stream_socket_client("tcp://$domain:$port", $errno, $errstr, 300000);
        if (!$this->client) {
            $this->log("$errstr ($errno)");
            return FALSE;
        }
        $this->log('client ok');
    }

    protected static function init() {
        error_reporting(E_ALL ^ E_NOTICE);
        //error_reporting(0);
        set_time_limit(0);
        ob_implicit_flush();
        date_default_timezone_set('Asia/Shanghai');
        ignore_user_abort(TRUE);
        mb_internal_encoding('gbk');
    }

    public function sendMessage($msg) {
        if ($msg === '') {
            return -1;
        }
        try {
            stream_socket_sendto($this->client, $msg);
        } catch (Exception $exc) {
            //$this->log($exc->getTraceAsString());
        }
    }

    public function getMessage() {
        $this->message = stream_socket_recvfrom($this->client, 10270000);
        //$this->log("Received news:");
        //$this->log($this->message);
        fwrite(STDOUT, $this->message . "\r\n");
    }

    public function shutdown() {
        stream_socket_shutdown($this->client, STREAM_SHUT_RDWR);
        fclose($this->client);
    }

    public static function log($message) {
        echo "\r\n" . $message . "\r\n";
    }

}

//

$client = new SocketClient('127.0.0.1',12345);
while (true) {

    $msg = fread(STDIN, 9999999);
    if (!trim($msg)) {
        continue;
    }
    $client->sendMessage($msg);
    $client->getMessage();
}

Posted by Marcus at December 19, 2016 - 2:49 AM

The moderator.
Here I need data analysis read client before write back end client, client you want there to send quit commands over socket, the online environment can not be achieved. Is there a better way? Thank you for your!!

Posted by Cheryl at January 03, 2017 - 3:00 AM

Great God who can help to solve this problem, the top

Posted by Cheryl at January 10, 2017 - 3:33 AM

I can't solve your problem?

Posted by Marcus at January 11, 2017 - 3:40 AM