listen SOCKET, EXPR |
配置网络套接字SOCKET 监听传入网络连接。设置传入的连接队列的长度为EXPR。您可能要考虑使用IO::Socket模块,它提供了一个更为简单的方法创建和监听网络套接字。
0 - 失败;
1 - 成功;
尝试随着套接字实现服务器的例子,详细的可以参考Perl Socket 。
#!/usr/bin/perl -w
# server.pl - by www.gitbook.net
#--------------------
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;
}