Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1279134
  • 博文数量: 168
  • 博客积分: 3483
  • 博客等级: 中校
  • 技术积分: 1696
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-06 13:17
文章分类

全部博文(168)

文章存档

2015年(6)

2014年(9)

2013年(47)

2012年(11)

2011年(13)

2010年(18)

2009年(11)

2008年(42)

2007年(11)

分类:

2008-03-08 15:15:34

# setsockopt -> recv timeout, man setsockopt and man 7 socket
$sock->sockopt(SO_RCVTIMEO, pack("I2", 1, 0));


# sendmsg.pl

# test for my monitor server app

use IO::Socket;
use Time::HiRes qw(usleep);

sub open_sock {
    my ($host, $port) = @_;
    my $socket = IO::Socket::INET->new(PeerAddr => $host,
                                       PeerPort => $port,
                                       Proto    => "tcp",
                                       Type     => SOCK_STREAM)
        or die "couldn't connect to $host:$port :$@\n";
}

sub send_msg {
    my $socket = shift @_;

    # specify the struct of message head
    my $msg_head_packfmt = "CCn";
    my $msg_head_size = 4;  # (C + C + n) == 4

    # read the argument and pack
    my ($type, $stat, $data) = @_;
    my $size = length($data);
    my $package = pack("${msg_head_packfmt}a*", $type, $stat, $size, $data);

    # send the package to server
    print $socket $package;
}

sub recv_msg {
    my $socket = shift @_;

    # specify the struct of message head
    my $msg_head_packfmt = "CCn";
    my $msg_head_size = 4;  # (C + C + n) == 4

    # receive a respond package
    recv($socket, $answer, $msg_head_size, $flags);
    my ($type, $stat, $size) = unpack($msg_head_packfmt, $answer);
    my $data;
    recv($socket, $data, $size, flags);

    return ($type, $stat, $size, $data);
}

sub xtest {
    my ($type, $stat, $data, $host, $port) = @_;

    my $sock = open_sock($host, $port);

    send_msg $sock, $type, $stat, $data;

    my $size;
    ($type, $stat, $size, $data) = recv_msg $sock;

    if ($data eq "OK") {
        printf "OK!!!\n";
    } else {
        printf "NG!!!\n";
    }

    printf "the package info: $type $stat $size\n$data\n";
    close($sock);
    usleep(1000 * 500);  # sleep 500 ms (0.5s)
}

my ($remote_host, $remore_port) = ("10.4.0.11", "1111");

xtest 0, 0, "detect", $remote_host, $remore_port;

xtest 1, 0, "ls *.c", $remote_host, $remore_port;

xtest 2, 0, "kkk kkk", $remote_host, $remore_port;

阅读(1819) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~