Advertisement
Guest User

Untitled

a guest
Sep 29th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 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( $!listener );
  11.  
  12. method run () { self!server(); }
  13.  
  14. method !server () {
  15. self!setup_listener();
  16. while @!connections = $!sock.can_read { # all ready clients
  17. for @!connections -> $fh {
  18. if $fh == $!listener { # is there any client who is waiting to be accepted?
  19. $!sock.add($!listener.accept);
  20. } else { # if not, do all stuff
  21. my @recved = self!recv();
  22. say @recved;
  23. }
  24. }
  25. }
  26. }
  27.  
  28. method !recv () { # get messages from all clients
  29. my @recv;
  30. for @!connections {
  31. @recv.push(.recv().chomp);
  32. }
  33. return @recv; # return array with messages
  34. }
  35.  
  36. method !setup_listener() { # setup a listener
  37. my $host = $.host; my $port = $.port;
  38. $!listener = IO::Socket::INET.new(
  39. :localhost($host), # default: localhost
  40. :localport($port), # default: 6611
  41. :listen, # 1
  42. );
  43. }
  44.  
  45. }
  46.  
  47. my $conn = TCP::Server::Simple.new( host => 'localhost', port => 8080 );
  48. $conn.run; # run a Simple TCP Server!
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement