教程集 www.jiaochengji.com
教程集 >  脚本编程  >  perl  >  正文 perl pack与unpack函数的例子

perl pack与unpack函数的例子

发布时间:2014-07-20   编辑:jiaochengji.com
本文分享一例perl使用pack与unpack函数的应用实例,学习下perl中pack与unpack函数的用法,有需要的朋友可以参考下。

本节内容:
 perl pack与unpack函数的应用实例

例子:
 

复制代码 代码示例:

#!/usr/bin/perl
#site: www.jiaochengji.com
# 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;

您可能感兴趣的文章:
perl pack与unpack函数的例子
perl的pack与unpack函数
PHP中的pack和unpack函数的用法详解
perl实例之子程序
PHP的实现一个高效的数据库(文件存储,NOSQL)
php实现对图片对称加解密(适用身份证加密等场景)
perl实例之http请求的小例子
php - tcp 粘包/拆包实例
php导出excel格式文件的例子
《Perl编程24学时教程》笔记第17课 perl的CGI概述

[关闭]
~ ~