PHP Conference Fukuoka 2025

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() 来取而代之。

参见

添加备注

用户贡献的备注 2 notes

up
6
leleu256NOSPAM at hotmail dot com
20 years ago
This code could be very helpfull...The following code is for the "server". It listen for a message until CTRL-C<?phpwhile (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...<?phpsend_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);  }}?>
up
5
Andy at txtNation dot com
13 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                }            }        }    }?>
To Top