perl function accept

‮‬https://www.theitroad.com

In Perl, the accept function is used to accept a new connection on a socket. It takes two arguments: the first is the name of the listening socket, and the second is a new socket that will be created to handle the connection.

Here's an example that demonstrates the use of the accept function:

use strict;
use warnings;
use IO::Socket::INET;

# create a listening socket
my $server = IO::Socket::INET->new(
    LocalAddr => 'localhost',
    LocalPort => 12345,
    Proto     => 'tcp',
    Listen    => 5,
    ReuseAddr => 1
);

die "Error: $!\n" unless $server;

print "Listening on port 12345...\n";

# wait for a client to connect
my $client = $server->accept();

print "Client connected from " . $client->peerhost() . "\n";

# do something with the client connection
# ...

# close the client connection
$client->close();

# close the server socket
$server->close();

In the above example, we first create a listening socket using the IO::Socket::INET module. We then wait for a client to connect by calling the accept function on the listening socket. The accept function blocks until a client connects, at which point it returns a new socket that can be used to communicate with the client.

Once we have the client socket, we can do something with it (e.g., send or receive data), and then close the socket when we're done.

Note that the accept function can also take an optional third argument, which is the timeout in seconds. If the timeout elapses before a client connects, the accept function returns undef. For example:

my $client = $server->accept(10);  # wait for up to 10 seconds for a client to connect
if ($client) {
    print "Client connected!\n";
} else {
    print "Timeout elapsed.\n";
}

In the above example, we wait for up to 10 seconds for a client to connect. If a client connects within that time, we print a message indicating that the client has connected. Otherwise, we print a message indicating that the timeout has elapsed.