Guest User

Untitled

a guest
Sep 29th, 2011
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. use IO::Select;
  2.  
  3. class TCP::Server::Simple {
  4.  
  5. has Int $.port is rw = 6611;
  6. has Str $.host is rw = 'localhost';
  7. has IO::Socket::INET $!listener;
  8. has @!connections; # all ready connections
  9. has Str $!request; # requests from clients
  10. has $!sock is rw = IO::Select.new();
  11.  
  12. method run () { self!server(); }
  13.  
  14. method !server () {
  15. self!setup_listener();
  16. $!sock.add( $!listener );
  17. loop {
  18. @!connections = $!sock.can_read(1); # all ready clients
  19. next unless @!connections;
  20. for @!connections -> $fh {
  21. if $fh == $!listener { # is there any client to accept?
  22. $!sock.add($!listener.accept);
  23. } else { # if not, do all stuff
  24. my @recved = self!recv();
  25. say @recved;
  26. }
  27. }
  28. }
  29. }
  30.  
  31. method !recv () { # get messages from all clients
  32. my @recv;
  33. for @!connections {
  34. @recv.push(.recv().chomp);
  35. }
  36. return @recv; # return array with messages
  37. }
  38.  
  39. method !setup_listener() { # setup a listener
  40. my $host = $.host; my $port = $.port;
  41. $!listener = IO::Socket::INET.new(
  42. :localhost($host), # default: localhost
  43. :localport($port), # default: 6611
  44. :listen, # 1
  45. );
  46. }
  47.  
  48. }
  49.  
  50. my $conn = TCP::Server::Simple.new( host => 'localhost', port => 8080 );
  51. $conn.run; # run a Simple TCP Server!
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment