Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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( $!listener );
- method run () { self!server(); }
- method !server () {
- self!setup_listener();
- while @!connections = $!sock.can_read { # all ready clients
- for @!connections -> $fh {
- if $fh == $!listener { # is there any client who is waiting to be accepted?
- $!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!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement