# 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) |