[Perl]测试程序时用Perl真是太方便了

<iframe align="center" marginwidth="0" marginheight="0" src="http://www.zealware.com/csdnblog336280.html" frameborder="0" width="336" scrolling="no" height="280"></iframe>

测试自己的业务数据远程传送服务,需要一个能模拟对方Socket的服务,
这时候就显出Perl的便利了。一分钟搞定。
代码如下,其实也是从CPAN那里拿来的:
####################################################################
#
# 工程项目: 模拟Socket服务器
#
# 模块任务: 来自intenel,这个脚本提供一个TCP echo 服务,版本是2
#
# 程序名称: TcpEchoServerForLDB.pl
#
# 程序说明:
# 监听固定Socket端口,如果收到数据,就给对方返回一个字符串“ok回车”,
# 这样来模拟接收数据的Socket服务。
#
# 使用说明:TcpEchoServerForLDB.pl [port]
# [port]指要监听的端口号
####################################################################

#!/usr/bin/perl
# Figure 5.4: The reverse echo server, using IO::Socket

##================================================================##
system("cls");
warn("/n");
warn("TCP ECHO Simple Server Version 2.0/n");
warn("没有版权 Linktone 2005-2006。不保留所有权利。/n");
warn("/n");
warn("用法: TcpEchoServerForLDB.pl [port]/n");
warn("[注意]如果没有传递端口参数,默认监听4330端口/n");
warn("[注意]发送的数据请以回车换行结尾!/n");
##================================================================##

##================================================================##
## 引用的库声明 2
use strict;
use IO::Socket qw(:DEFAULT :crlf);
##================================================================##

##================================================================##
use constant MY_ECHO_PORT => 4330;
$/ = CRLF;
my ($bytes_out,$bytes_in) = (0,0);

my $quit = 0;
$SIG{INT} = sub { $quit++ };

my $port = shift || MY_ECHO_PORT;

my $sock = IO::Socket::INET->new( Listen => 20,
LocalPort => $port,
Timeout => 60*60,
Reuse => 1)
or die "Can't create listening socket: $!/n";

warn "服务守候在端口$port.../n";
while (!$quit)
{
next unless my $session = $sock->accept;

my $peer = gethostbyaddr($session->peeraddr,AF_INET) || $session->peerhost;
my $port = $session->peerport;
warn "她来了:[$peer,$port]/n";

# 要回送的字符串
my $msg_Output = "ok回车";

while ()
{
$bytes_in += length($_);
chomp;
my $msg_out = (scalar reverse $_) . CRLF;
warn("Message From [$peer,$port]:$msg_out");
print $session $msg_Output;
##warn("Send Message To [$peer,$port]:$msg_Output");
$bytes_out += length($msg_Output);
}
warn "她走了[$peer,$port]!/n";
close $session;
}
##================================================================##

print STDERR "bytes_sent = $bytes_out, bytes_received = $bytes_in/n";
warn("bytes_sent = $bytes_out, bytes_received = $bytes_in/n");
close $sock;




你可能感兴趣的:(perl)