• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • socket_create_listen()

    (PHP 4 >= 4.1.0, PHP 5, PHP 7)

    在一个端口上打开 socket 监听

    说明

    socket_create_listen(int $port[,int $backlog= 128]):Socket|false

    socket_create_listen()创建一个新的AF_INET类型的 Socket实例监听,监听指定端口上的所有本地接口,等待新的连接。

    此函数旨在简化创建仅侦听接受新连接的新套接字的任务。

    参数

    $port

    在所有接口上侦听的端口。

    $backlog

    $backlog参数定义了待处理连接队列可能增长到的最大长度。SOMAXCONN可以作为参数传递,有关更多信息,请参阅socket_listen()

    返回值

    • 成功时,返回一个新的 Socket实例。php8.0 版本之前,返回了一个资源。
    • 错误时,返回false。可以使用socket_last_error()检索错误代码。可以将此代码传递给socket_strerror()以获取错误的文本解释。

    注释

    Note:

    如果你想创建一个只监听某个接口的socket连接,你需要使用socket_create()socket_bind()socket_listen()

    参见

    If you specify no port number, or 0, a random free port will be chosen.
    To use ports for ipc between client/server on the same machine you can use (minus error checking)
    server.php:
    <?php
    $sock = socket_create_listen(0);
    socket_getsockname($sock, $addr, $port);
    print "Server Listening on $addr:$port\n";
    $fp = fopen($port_file, 'w');
    fwrite($fp, $port);
    fclose($fp);
    while($c = socket_accept($sock)) {
      /* do something useful */
      socket_getpeername($c, $raddr, $rport);
      print "Received Connection from $raddr:$rport\n";
    }
    socket_close($sock);
    ?>
    
    
    client.php:
    
    <?php
    $fp = fopen($port_file, 'r');
    $port = fgets($fp, 1024);
    fclose($fp);
    
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($sock, '127.0.0.1', $port);
    socket_close($sock);
    ?>
    
    Please note that port 1 to and with 1024 on linux and bsd system require root privileges. So it is recommended to choose a higher port for your own application.
    Remember that ports are only valid from 1 - 65535
    [editor's note: typo fixed, thanks abryant at apple dot com]
    I believe that on some systems this may not bind to some or all public interfaces.
    On my Windows system, I could not connect on the public interface using this, but could when I made the individual calls to create, bind, and listen.
    Dustin Oprea