作者: Jim Wang 公众号: 巴博萨船长

摘要:本文主要介绍,如何尝试自己的创建Perl语言的包与UDP协议的再包装使其起到类似python语言装饰器的效果

Abstract: This article mainly introduces how to try to create your own Perl language package and repackaging the UDP protocol to make it look like a python language decorator.

作者: Jim Wang 公众号: 巴博萨船长

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/perl 
# Filename: BuildSocketUDP.pm
package BuildSocketUDP;
require Exporter;

@ISA = qw(Exporter);
@EXPORT = qw(readfile checkfile);

use IO::Socket::INET; # provides an object interface to creating and using Socket
use strict 'vars'; # this generates a runtime error if you use symbolic references
use constant false => 0;
use constant true => 1;

# flush after every write
$| = 1;

#Create a new instance
sub new {
my $self = {}; # Connect the hash to the package Cocoa.
shift;
my ($ip, $port, $proto, $isserver) = @_;
my $socket;
my $self->{'ip'} = $ip;
my $self->{'port'} = $port;
if ($isserver == true && $proto == 'udp')
{
#print "Buldi socket for server\n";
$socket = new IO::Socket::INET(
LocalPort => $port || '8765',
Blocking => '0',
Proto => $proto) or die "* Error Server in Socket Creation : $!\n";
print "UDP Server connected successful be created with port : $port\n";
print "---------------------\n";
}
else
{
#print "Buldi socket for client\n";
$socket = new IO::Socket::INET(
PeerHost => $ip || '127.0.0.1',
PeerPort => $port || '8765',
Blocking => '0',
Proto => $proto) or die "* Error Client in Socket Creation : $!\n";
print "UDP Client connected successful be created with host : $ip\n";
print "UDP Client connected successful be created with port : $port\n";
print "---------------------\n";
}
#print "$socket"."\n";
$self->{'socket'} = $socket;
#print $self->{'socket'}."AAAA\n";
bless ($self);
return $self; # Return the reference to the hash.
}

#Subroutine to close the socket
sub closeSocket
{
my $self = shift;
($self->{'socket'})->close() or die "* Error to close the socket"
}

#Subroutine to send the data
sub sendViasocket
{
my $self = shift;
my ($data_out, $length , $description) = @_;
($self->{'socket'})->send($data_out);
#($self->{'socket'})->flush;
#print "Send data successful via udp socket>> : $description >>: $data_out\n";
}

#Subroutine to recv the data
sub recvViasocket
{
my $self = shift;
my ($length, $description) = @_;
my $data_in;
($self->{'socket'})->recv($data_in, $length);
#($self->{'socket'})->flush;
#print "Recvied data successful via udp socket: $description >>: $data_in\n";
return $data_in;
}

1; # 当然不要忘了这个不知所以然的1

这只是给大家提供一种思路,毕竟是第一次尝试写类似的东西,难免存在不足之处,希望大家谅解,这样类似与Python语言装饰器的效果,给一些基本的包里面的方法提供了更多扩展和美化的作用,也为后来使用提供了方便。

先上代码,由于整理博客,代码分析以后整理添加。欢迎交流提意见彼此提高。需要声明一下51cto博客作者zuiwuxin就是作者本人,所以不存在版权问题。以后该博客将作为个人文章的主要发布地。


版权声明:
文章首发于 Jim Wang's blog , 转载文章请务必以超链接形式标明文章出处,作者信息及本版权声明。