標籤:perl socket select
server程式
接受用戶端資訊,並發送回應
#!/usr/bin/perl -w
# socket_server.pl
use strict;
use IO::Socket;
use IO::Select;
# hash to install IP Port
my ($ser_addr, $ser_port)=("127.0.0.1", "12345");
our($buffer, $len);
my $socket = IO::Socket::INET->new(
LocalAddr => "$ser_addr", #本機IP地址
LocalPort => "$ser_port", #定義原生Port,然後進行bind
Type => SOCK_STREAM, #通訊端類型
Proto => "tcp", #協議名
Listen => 200, #定義listen的最大數
Blocking => 0, #非阻塞
) or die "Can not create socket [email protected]";
my $sel = IO::Select->new($socket);
while (my @ready = $sel->can_read) {
foreach my $fh (@ready) {
if ($fh == $socket) {
my $new = $socket->accept();
$sel->add($new);
}
else {
$len = $fh->recv($buffer,1024,0); #接收用戶端訊息
print "$buffer \n";
$fh->send("Server OK!\n",0); #發送服務端訊息
$fh->autoflush(1);
$sel->remove($fh);
$fh->close();
}
}
}
$socket->close() or warn "Close Socket [email protected]";
2.client
串連用戶端,發送一個訊息,並接受伺服器端應答訊息
#!/usr/bin/perl -w
# Socket_client.pl
use strict;
use IO::Socket; ##IO::Socket::INET模組是IO::Socket模組的子模組,不用重新use。
use IO::Select; ##該模組和Linux下select()函數實現的功能一致,另擴充更過的功能。可以perldoc查看。
for (my $i=0; $i<20000; $i++){
&send_rev_data;
}
sub send_rev_data{
my ($ser_addr, $ser_port) = ("127.0.0.1", "12345");
##IO::Socket::INET->new()用於初始化一個socket串連,其中整合了socket、inet_aton、connect、bind、listen等功能。就不需要單獨轉換IP地址為網路地址結構了,直接使用IP地址就ok了。
##具體參數下面單獨介紹。
my $socket = IO::Socket::INET->new(
PeerAddr => "$ser_addr",
PeerPort => "$ser_port",
Type => SOCK_STREAM,
Proto => "tcp",
) or die "Can not create socket [email protected]";
$socket->send("Client Ok!\n",0); ##發送訊息至伺服器端。
$socket->autoflush(1);
my $sel = IO::Select->new($socket); ##建立select對象
while (my @ready = $sel->can_read) { ##等待服務端返回的訊息
foreach my $fh (@ready) {
if ($fh == $socket) {
while (<$fh>) {
print $_;
}
$sel->remove($fh);
close $fh;
}
}
}
#$socket->close() or die "Close Socket [email protected]";
}
本文出自 “yiyi” 部落格,請務必保留此出處http://heyiyi.blog.51cto.com/205455/1598532
Perl IO:Socket IO:Select server client