Advertisement
Guest User

socket server

a guest
Dec 3rd, 2018
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.66 KB | None | 0 0
  1. use v6;
  2. use Data::Dump;
  3. use experimental :pack;
  4. use JSON::Tiny;
  5. use Redis::Async;
  6.  
  7. constant $SOCKET_PORT = 7000;
  8. constant $SOCKET_ADDR = '0.0.0.0';
  9. constant $REDIS_PORT = 6379;
  10. constant $REDIS_ADDR = '127.0.0.1';
  11. constant $REDIS_AUTH = 'xxxxxxxx';
  12.  
  13.  
  14. constant $IDLING_PERIOD_MIN = 180 - 2; # 3 minutes - 2 secs
  15. constant $CACHE_EXPIRE_IN = 86400; # 24h hours
  16.  
  17. # create socket
  18. my $socket = IO::Socket::Async.listen($SOCKET_ADDR, $SOCKET_PORT);
  19.  
  20. # connnect to Redis ...
  21. my $redis;
  22. try {
  23.     my $error-code = "110";
  24.     $redis = Redis::Async.new("$SOCKET_ADDR:$SOCKET_PORT");
  25.     $redis.auth($REDIS_AUTH);
  26.  
  27.     CATCH {
  28.         default {
  29.             say "Error $error-code ", .^name, ': Failed to initiate connection to Redis';
  30.             exit;
  31.         }
  32.     }
  33. }
  34.  
  35. # react whenever there is connection
  36. react {
  37.     whenever $socket -> $conn {
  38.  
  39.         # do something when the connection wants to talk
  40.         whenever $conn.Supply(:bin) {
  41.             # only process if data length is either 108 or 116
  42.             if $_.decode('utf-8').chars == 108 or $_.decode('utf-8').chars == 116 {
  43.                 say "Received --> "~$_.decode('utf-8');
  44.                 my $ack = generateAck($_.decode('utf-8'));  # generate ack based on received data
  45.                 if $ack {
  46.                     $conn.print: $ack;
  47.                 }else{
  48.                     say "No ack. Received data maybe corrupted. Closing connection";
  49.                     $conn.close;
  50.                 }
  51.  
  52.             }
  53.         }
  54.     }
  55.     CATCH {
  56.         default {
  57.             say .^name, ': ', .Str;
  58.             say "handled in $?LINE";
  59.         }
  60.     }
  61. }
  62.  
  63. ### other subroutines down here ###
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement