SHARE
TWEET

P6 Socket Server

a guest Nov 23rd, 2018 131 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use Data::Dump;
  2. use experimental :pack;
  3.  
  4. my $socket = IO::Socket::Async.listen('0.0.0.0', 7000);
  5.  
  6. react {
  7.     whenever $socket -> $conn {
  8.         my $line = '';
  9.         whenever $conn {
  10.            
  11.             say "Received --> "~$_;
  12.             $conn.print: &translate($_) if $_.chars ge 100;  
  13.             $conn.close;              
  14.      
  15.         }
  16.     }
  17.     CATCH {
  18.         default {
  19.             say .^name, ': ', .Str;
  20.             say "handled in $?LINE";
  21.         }
  22.     }
  23. }
  24.  
  25. sub translate($raw) {
  26.  
  27.     my $rawdata = $raw;
  28.     $raw ~~ s/^\s+|\s+$//; # remove heading/trailing whitespace
  29.    
  30.     my $minus_checksum = substr($raw, 0, *-2);
  31.     my $our_checksum = generateChecksum($minus_checksum);
  32.     my $data_checksum = ($raw, *-2);
  33.  
  34.     # say $our_checksum;
  35.     return $our_checksum;
  36.  
  37. }
  38.  
  39. sub generateChecksum($minus_checksum) {
  40.    
  41.     # turn string into Blob
  42.     my Blob $blob = $minus_checksum.encode('utf-8');
  43.     # unpack Blob into ascii list
  44.     my @array = $blob.unpack("C*");
  45.     # perform bitwise operation for each ascii in the list
  46.     my $dec +^= $_ for $blob.unpack("C*");
  47.     # only take 2 digits
  48.     $dec = sprintf("%02d", $dec) if $dec ~~ /^\d$/;
  49.     $dec = '0'.$dec if $dec ~~ /^[a..fA..F]$/;
  50.     $dec = uc $dec;
  51.     # convert it to hex
  52.     my $hex = sprintf '%02x', $dec;
  53.     return uc $hex;
  54.  
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top