はじめてのネットワークプログラミング
あんまし気乗りしないんだけどね、苦手分野だから。
でも、弱点を克服できるなら悪くないかなーってことでやってみます。
クライアントサイド(client.pl)
use v5.14;
use strict;
use warnings;
use IO::Socket;
use constant PORT_COOL => 40000;
use constant PORT_HOT => 50000;
my $c1 = IO::Socket::INET->new(
PeerAddr => 'localhost',
PeerPort => PORT_COOL,
Proto => 'tcp'
) or die $!;
my $c2 = IO::Socket::INET->new(
PeerAddr => 'localhost',
PeerPort => PORT_HOT,
Proto => 'tcp'
) or die $!;
$c1->print( "hello\n" );
say $c1->getline();
$c2->print( "hello\n" );
say $c2->getline();
$c1->close;
$c2->close;
サーバーサイド(server.pl)
use v5.14;
use strict;
use warnings;
use IO::Socket;
use constant PORT_COOL => 40000;
use constant PORT_HOT => 50000;
my $srv_cool = IO::Socket::INET->new(
LocalAddr => "localhost",
LocalPort => PORT_COOL,
Proto => "tcp",
Listen => 1,
ReuseAddr => 1,
Blocking => 0
) or die $!;
my $srv_hot = IO::Socket::INET->new(
LocalAddr => "localhost",
LocalPort => PORT_HOT,
Proto => "tcp",
Listen => 1,
ReuseAddr => 1,
Blocking => 0
) or die $!;
$srv_cool->listen or die $!;
$srv_hot->listen or die $!;
# エントリー待ち
my ( $cl_cool, $cl_hot );
while ( not ($cl_cool && $cl_hot) ) {
if ( not $cl_cool ) {
$cl_cool = $srv_cool->accept();
if ( $cl_cool ) {
say 'accept COOL!';
next;
}
}
if ( not $cl_hot ) {
$cl_hot = $srv_hot->accept();
if ( $cl_hot ) {
say 'accept HOT!';
next;
}
}
sleep( 1 );
say 'zzz...';
}
foreach my $c ( $cl_cool, $cl_hot ) {
while ( 1 ) {
my $q = $c->getline();
next if not $q;
say $q;
$c->print( "hello\n" );
last;
}
$c->close();
}
$srv_cool->close();
$srv_hot->close();
実行するには、ターミナルを2つ立ち上げて、
サーバーサイドから実行する。
ターミナル(1)
$ perl server.pl
zzz...
zzz...
zzz...
zzz...
accept COOL!
accept HOT!
hello
(改行)
hello
(改行)
ターミナル(2)
$ perl client.pl
hello
(改行)
hello
(改行)
なんで、”COOL”と”HOT”なのかは、
ここにある「ルールブック(確定版).pdf」を読んで頂ければと思う。
CHaser2013 – 全国情報技術教育研究会
http://www.zenjouken.com/?page_id=517
想定する要件はこんな感じ。
2つのクライアントからサーバーに接続すると対戦が始まって、
2つのクライアントに交互にターンが回ってくるというもの。
とりあえず、ポート番号さえ異なれば、
こんな感じで接続を維持できることが分かったので、
次はクライアントサイドに専念しようと思う。
おしまい。
Leave a Comment