用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - perl代码库

perl 设置一个UDP的服务器

2012-10-14 作者: 神马举报

[perl]代码库

#-----------------------------
use IO::Socket;
$server = IO::Socket::INET->new ( LocalPort => $server_port,
                                  Proto     => "udp" )
          or die "Couldn't be a udp server on port $server_port : $@\n";
#-----------------------------
while ( $him = $server->recv ( $datagram, $MAX_TO_READ, $flags ) )
{
# do something
}
#-----------------------------
# download the following standalone program
#!/usr/bin/perl -w
# udpqotd - UDP message server
use strict;
use IO::Socket;
my ( $sock, $oldmsg, $newmsg, $hisaddr, $hishost, $MAXLEN, $PORTNO );
$MAXLEN = 1024;
$PORTNO = 5151;
$sock = IO::Socket::INET->new ( LocalPort => $PORTNO, Proto => 'udp' )
        or die "socket: $@";
print "Awaiting UDP messages on port $PORTNO\n";
$oldmsg = "This is the starting message.";
while ( $sock->recv ( $newmsg, $MAXLEN ) )
{
	my ( $port, $ipaddr ) = sockaddr_in ( $sock->peername );
	$hishost = gethostbyaddr ( $ipaddr, AF_INET );
	print "Client $hishost said ``$newmsg''\n";
	$sock->send ( $oldmsg );
	$oldmsg = "[$hishost] $newmsg";
}
die "recv: $!";

#-----------------------------
# download the following standalone program
#!/usr/bin/perl -w
# udpmsg - send a message to the udpquotd server

use IO::Socket;
use strict;

my ( $sock, $server_host, $msg, $port, $ipaddr, $hishost,
     $MAXLEN, $PORTNO, $TIMEOUT );

$MAXLEN  = 1024;
$PORTNO  = 5151;
$TIMEOUT = 5;

$server_host = shift;
$msg         = "@ARGV";
$sock = IO::Socket::INET->new ( Proto     => 'udp',
                                PeerPort  => $PORTNO,
                                PeerAddr  => $server_host )
        or die "Creating socket: $!\n";
$sock->send ( $msg ) or die "send: $!";

eval
{
	local $SIG{ALRM} = sub { die "alarm time out" };
	alarm $TIMEOUT;
	$sock->recv ( $msg, $MAXLEN )      or die "recv: $!";
	alarm 0;
	1;
# return value from eval on normalcy
} or die "recv from $server_host timed out after $TIMEOUT seconds.\n";

( $port, $ipaddr ) = sockaddr_in ( $sock->peername );
$hishost = gethostbyaddr ( $ipaddr, AF_INET );
print "Server $hishost responded ``$msg''\n";

#-----------------------------


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...