文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>socket programming

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(...);
    ...;
    while(1)
    {
        next unless my $client = $sock->accept;
        defined (my $child = fork) or die "Can't fork: $!\n";
        if($child == 0)
        {
            warn "fork to communicate\n";
            $sock->close;
            ...
            while(1)
            {
                $session->recv();
                 ...
                $session->send(); 
            }

            exit(0);
        }

    }

client:

my $sock = IO::Socket::INET->new(
            PeerAddr => $addr,
            PeerPort => $port,
            Proto => 'tcp')
my $ret = $sock->send(...);
while(1)
{
     $sock->recv($buf,4,0);

      ...;
     my $ret = $sock->send($sendTo);
}

4,SIGALARM:

$SIG{ALRM} = \&SendHeartBeat;
sub SendHeartBeat()
{
    ...;
    alarm(5);
}

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.

相关阅读 更多 +
排行榜 更多 +
方块枪战战场安卓版

方块枪战战场安卓版

飞行射击 下载
战斗火力射击安卓版

战斗火力射击安卓版

飞行射击 下载
空中防御战安卓版

空中防御战安卓版

飞行射击 下载