Perl socket client and server

TCP:
server端:

#!/usr/bin/perl -w
use Socket;
use IO::Handle;
socket(SOCK,AF_INET,SOCK_STREAM,getprotobyname("tcp"));
#setsockopt(SOCK,SOL_SOCKET,SO_REUSEADDR,1);
my $addr=sockaddr_in(3000,INADDR_ANY);
bind(SOCK,$addr);

listen(SOCK,SOMAXCONN);

while(1){
next unless my $addr1=accept(S,SOCK);

S->autoflush(1);
#       STDOUT->autoflush(1);
print S "welcome/n";
while(<S>){
print $_;
chomp;
if($_=~/^quit/i){
print S "bye";
close S;
close SOCK;
exit 0;
}
print S (`$_`)."/n";
}

close S;
}
client端:

#!/usr/bin/perl -w
use Socket;
use IO::Handle;
socket(SOCK,AF_INET,SOCK_STREAM,getprotobyname("tcp"));

my $addr=sockaddr_in(3000,inet_aton("192.168.1.73"));
connect(SOCK,$addr);
SOCK->autoflush(1);
$buff=<SOCK>;
STDOUT->autoflush(1);
print $buff;
while(1)
{
$in=<STDIN>;
send(SOCK,$in,0);
while(my $l=sysread(SOCK,$buff,100))
{
if($buff=~/bye/i){
close SOCK;
exit 0;
}
print $buff;
last if $l<100;
}

}
UDP:
#udp server
#!use/bin/perl -w
use Socket; #导入Socket库
$localhost=sockaddr_in(4000,INADDR_ANY);#压入sockaddr_in模式,利用了全局当地压缩地点INADDR_ANY保存字
socket(SERVER,AF_INET,SOCK_DGRAM,17); #成立UDP套接字
bind(SERVER,$localhost); #绑定套接字
while(1){ #进入办事器轮回体
next unless $client=recv(SERVER,$buff,100,0); #若是领受到数据就把数据压入$buff,保存长途地点在$client
chop($buff); #减去$buff末了的输入标记
print "$buff/n"; #在$buff变量打入STDOUT
send(SERVER,"$buff/n",0,$client); #把$buff发送给客户端
}
close SERVER; #封闭套接字
exit 1; #退出法式


#udp client
#!use/bin/perl -w
use Socket; #导入Socket库
$host=$ARGV[0]; #第一参数为主机变量
$port=$ARGV[1]; #第二参数为端口变量
$packhost=inet_aton($host); #压缩主机地点
$address=sockaddr_in($port,$packhost); #压为sockaddr_in模式
socket(CLIENT,AF_INET,SOCK_DGRAM,17); #成立UDP套接字
send(CLIENT,"hi,body!/n",0,$address); #向套接字发送字符串变量
recv(CLIENT,$buff,100,0); #领受数据
print"$buff/n"; #把领受后的数据打入STDOUT
close CLIENT; #封闭套接字
exit 1; #退出法式

你可能感兴趣的:(socket,server,Stream,IO,tcp,perl)