當前位置:首頁 » Perl » Perl listen()函數

Perl listen()函數

perl listen()函數例子,listen()函數學習,listen()函數實例代碼,listen()函數教學等

語法

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;
}