PHP 8.5.0 Released!

stream_socket_accept

(PHP 5, PHP 7, PHP 8)

stream_socket_acceptПринимает соединение в сокете, который создали функцией stream_socket_server()

Описание

stream_socket_accept(resource $socket, ?float $timeout = null, string &$peer_name = null): resource|false

Функция принимает соединение в сокете, который предварительно создали функцией stream_socket_server().

Список параметров

socket

Серверный сокет для принятия соединения.

timeout

Переопределяет время ожидания подключения сокета по умолчанию. Время требуется указывать в секундах. По умолчанию используется значение директивы default_socket_timeout.

peer_name

Функция присвоит параметру имя (адрес) клиента, который подключился, если оно включено и доступно из выбранного транспорта.

Замечание:

Имя можно определить позже функцией stream_socket_get_name().

Возвращаемые значения

Функция возвращает поток принятого соединения с сокетом или false, если возникла ошибка.

Список изменений

Версия Описание
8.0.0 Параметр timeout теперь принимает значение null.

Примечания

Внимание

Функцию не следует вызывать с серверными UDP-сокетами. Вместо неё вызывают функции stream_socket_recvfrom() и stream_socket_sendto().

Смотрите также

  • stream_socket_server() - Создаёт серверный сокет Internet- или Unix-домена
  • stream_socket_get_name() - Получает название локального или удалённого сокета
  • stream_set_blocking() - Устанавливает блокирующий или неблокирующий режим для потока
  • stream_set_timeout() - Устанавливает значение времени ожидания для потока
  • fgets() - Получает строку из указателя на файл
  • fgetss() - Читает строку из файла и удаляет HTML-теги
  • fwrite() - Записывает данные в файл в бинарно-безопасном режиме
  • fclose() - Закрывает открытый дескриптор файла
  • feof() - Проверяет, достигнут ли конец файла
  • Функции cURL

Добавить

Примечания пользователей 2 notes

up
5
Andy at txtNation dot com
14 years ago
To check if there's a new connection waiting, without blocking, or (when using non-blocking mode) without notices), you can use stream_accept (as opposed to socket_select).

<?php

    class GenericClass {

        protected $resSocket=null;

        function acceptConnections() {

            # check that we still have a resource 
            
            if(is_resource($this->resSocket)) {
            
                $arrRead=array($this->resSocket);
                
                $arrWrite=array();
                
                /** @warning Passing $arrRead,$arrWrite by reference */
                if(stream_select($arrRead,$arrWrite,$arrWrite,0)) {
            
                    $resConnection=stream_socket_accept($this->resSocket,0);

                    # ... other stuff here
                }
            }
        }
    }
?>
up
5
leleu256NOSPAM at hotmail dot com
21 years ago
This code could be very helpfull...

The following code is for the "server". It listen for a message until CTRL-C

<?php
while (true)
{
// disconnected every 5 seconds...
receive_message('127.0.0.1','85',5);
}

function receive_message($ipServer,$portNumber,$nbSecondsIdle)
{
  // creating the socket...
  $socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);
  if (!$socket)
  {
    echo "$errstr ($errno)<br />\n";
  }
  else
   {
    // while there is connection, i'll receive it... if I didn't receive a message within $nbSecondsIdle seconds, the following function will stop.
    while ($conn = @stream_socket_accept($socket,$nbSecondsIdle))
    {
     $message= fread($conn, 1024);
     echo 'I have received that : '.$message;
     fputs ($conn, "OK\n");
     fclose ($conn);
    }
    fclose($socket);
  }
}
?>

The following code is for the "client". It send a message, and read the respons...

<?php

send_message('127.0.0.1','85','Message to send...');

function send_message($ipServer,$portServer,$message)
{
  $fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
  if (!$fp)
  {
     echo "ERREUR : $errno - $errstr<br />\n";
  }
  else
  {
     fwrite($fp,"$message\n");
     $response =  fread($fp, 4);
     if ($response != "OK\n")
        {echo 'The command couldn\'t be executed...\ncause :'.$response;}
     else
        {echo 'Execution successfull...';}
     fclose($fp);
  }
}
?>
To Top