Perl listen 函数



  • 描述

    listen 此函数将网络套接字SOCKET配置为侦听传入的网络连接。将传入连接队列长度设置为EXPR。您可能需要考虑使用IO :: Socket模块,该模块提供了一种创建和侦听网络套接字的简便方法。
  • 句法

    以下是此函数的简单语法-
    
    listen SOCKET, EXPR
    
    
  • 返回值

    如果失败,此函数返回0,如果成功,则返回1。
  • 示例

    以下是显示其基本用法的示例代码-
     
    use strict;
    use Socket;
    
    # use port 7890 as default
    my $port = shift || 7890;
    my $proto = getprotobyname('tcp');
    
    # create a socket, make it reusable
    socket(SOCKET, PF_INET, SOCK_STREAM, $proto) 
       or die "Can't open socket $!\n";
    setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1) 
       or die "Can't set socket option to SO_REUSEADDR $!\n";
    
    # bind to a port, then listen
    bind( SOCKET, pack( 'Sn4x8', AF_INET, $port, "\0\0\0\0" ))
           or die "Can't bind to port $port! \n";
    listen(SOCKET, 5) or die "listen: $!";
    print "SERVER started on port $port\n";
    
    # accepting a connection
    my $client_addr;
    while ($client_addr = accept(NET_SOCKET, SOCKET)) {
       # send them a message, close connection
       print NEW_SOCKET "Smile from the server";
       close NEW_SOCKET;
    }