I have been pulling my hair out for this one. I am trying to write a game, which would communicate to other players via sockets. However, there can be anywhere from 2 to 6 players in the game, so, waiting for new players to join is causing me some headache. Since I didn't want to force the players into joining a game within a certain timeout period, I make a blocking socket without a timeout value. Thus, the host must tell the game when to stop awaiting more players. Here's what I came up with (see below).
The host forks: the parent sits awaiting a click of the "Cancel" button to stop the child process, the child sits awaiting the socket connections, getting the names of the players. The child receives the names just fine, but since the $name var is not shared, i need to pass it back to the parent. AND THIS DOES NOT SEEM TO WORK!
Please help me out, or,if you see a better way of doing this, let me know. Thanks in advance.P.S. to run the "host", simply run the program, to run as a joining player, run program with any option.
use Tk; use IO::Socket; use strict; use English; require Tk::DialogBox; if (defined $ARGV[0]){ my $sock = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => '7071', Proto => 'tcp', ); die "Could not create socket: $!\n" unless $sock; print $sock "name=Player1!"; close($sock); exit; } my $mw = MainWindow->new; &waiting; MainLoop; sub waiting{ my $sock; my $pid; my $name; pipe READOUT, WRITEOUT or die "can't pipe"; $pid = fork(); if ($pid){ my $db = $mw->DialogBox( -title => "Waiting for users", -buttons => [ "Cancel" ] , -command => sub {kill(30,$pid);}, ); $db->add( "Label", -text => " \n\n")->pack(); $db->Show(); close(WRITEOUT); my $in = <READOUT>; print "parent received $in\n"; close(READOUT); } else { close(READOUT); open(STDOUT, ">&WRITEOUT"); sub SeeYa { print "\n";close(STDOUT);close(WRITEOUT);} $SIG{'USR1'} = SeeYa; for (my $i=1; $i<6; $i++){ $sock = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => 7071, Proto => 'tcp', Listen => 1, Reuse => 1, ); die "Could not create socket: $!\n" unless $sock; my $new_sock = $sock->accept(); my $input; while(defined(my $in = <$new_sock>)) { $input = $in; } ($_,$name) = split(/=/,$input); close($sock); print "$name\n"; } } }
In reply to Fork and pipe by gri6507
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |