Created
October 19, 2011 08:43
-
-
Save tadzik/1297750 to your computer and use it in GitHub Desktop.
im2ee's TCP server, exposes funny failures in IO::Select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use IO::Select; | |
class TCP::Server::Simple { | |
has Int $.port is rw = 6611; | |
has Str $.host is rw = 'localhost'; | |
has IO::Socket::INET $!listener; | |
has @!connections; # all ready connections | |
has Str $!request; # requests from clients | |
has $!sock is rw = IO::Select.new(); | |
method run () { self!server(); } | |
method !server () { | |
self!setup_listener(); | |
loop { | |
#@!connections = $!sock.can_read(1); # all ready clients | |
#next unless @!connections; | |
if $!sock.poll(nqp::unbox_i(1), nqp::unbox_i(1), nqp::unbox_i(0)); | |
say @!connections.perl; | |
for @!connections -> $fh { | |
if $fh == $!listener { # is there any client to accept? | |
$!sock.add($!listener.accept); | |
} else { # if not, do all stuff | |
my @recved = self!recv(); | |
say @recved; | |
} | |
} | |
} | |
} | |
method !recv () { # get messages from all clients | |
my @recv; | |
for @!connections { | |
@recv.push(.recv().chomp); | |
} | |
return @recv; # return array with messages | |
} | |
method !setup_listener() { # setup a listener | |
my $host = $.host; my $port = $.port; | |
$!listener = IO::Socket::INET.new( | |
:localhost($host), # default: localhost | |
:localport($port), # default: 6611 | |
:listen, # 1 | |
); | |
} | |
} | |
my $conn = TCP::Server::Simple.new( host => 'localhost', port => 8080 ); | |
$conn.run; # run a Simple TCP Server! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment