socket programming
时间:2007-06-22 来源:digex
SUMMARY:
1,pack()/unpack():
In network communication,a length field was usually added ahead to specify the total length of rest string.Thus "hello world" was sent as "11hello world".In fact the number '11' was usually sent in unsigned long integer(most cases 4 bytes) so that the client written in other languages could also get it by reading the first 4 bytes.
Get length field:
$session->recv($buf,4,0);
my $len = unpack('N',$buf);
Pack length field:
my $sendTo = pack 'Na*',length($item),$item;
$session->send($sendTo) or die "Failed to send to socket: $!";
perldoc about 'N':
n An unsigned short in "network" (big-endian) order.
N An unsigned long in "network" (big-endian) order.
v An unsigned short in "VAX" (little-endian) order.
V An unsigned long in "VAX" (little-endian) order.
2,IO
STDIN->fdopen($session,"<") or die "Can't reopen STDIN:$!";
STDOUT->fdopen($session,">") or die "Can't reopen STDOUT:$!";
STDERR->fdopen($session,">") or die "Can't reopen STDERR:$!";
cause everything goes into socket.
3,Main prcoess:
server:
my $sock = IO::Socket::INET->new(...);
exit(0); } |
client:
my $sock = IO::Socket::INET->new(
...; |
4,SIGALARM:
$SIG{ALRM} = \&SendHeartBeat; |
In main process there must be an alarm or else SendHeartBeat() never started.
5,send()
perldoc -f send
send SOCKET,MSG,FLAGS,TO
send SOCKET,MSG,FLAGS
send($sock,$buf,0) diff with send($buf),need confirm.