File: client-sysread.pl

package info (click to toggle)
libredis-fast-perl 0.34%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 492 kB
  • sloc: perl: 2,630; makefile: 7
file content (72 lines) | stat: -rwxr-xr-x 1,594 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/perl

use strict;
use warnings;
use Time::HiRes;
use IO::Socket::INET;

my $exp_cnt = $ARGV[0];
my $exp_len = $ARGV[1];
my $start_time = Time::HiRes::time();

my $sock = IO::Socket::INET->new(
    PeerAddr => 'localhost',
    PeerPort => '1234',
    Proto     => 'tcp',
);

die $! unless $sock;
die $! unless print $sock "$exp_cnt,$exp_len\n";
$exp_len += 1;

my $cnt = 0;
while (my $line = read_line($sock)) {
    my $len = length($line);
    print "LENGTH MISMATCH $len != $exp_len\n" if $len != $exp_len;
    ++$cnt;
}

printf "%.5f\n", (Time::HiRes::time() - $start_time);
print "CNT MISMATCH: $cnt != $exp_cnt\n" if $cnt != $exp_cnt;
exit 0;

# implementation of application layer buffering
# general concept:
# 1. try read 4K block of data
# 2. scan if for \n
# 3. if found, return line
# 4. go to step 1

my $str;
my $potential_data_in_str;
sub read_line {
    my $sock = shift; 

    if ($str && $potential_data_in_str) {
        my $idx = index($str, "\n");
        if ($idx >= 0) {
            return substr($str, 0, $idx + 1, '');
        }

        $potential_data_in_str = 0;
    }

    while (1) {
        my $buf;
        my $len = sysread($sock, $buf, 4096);
        return unless defined $len;
        return unless $len;

        my $idx = index($buf, "\n");
        if ($idx >= 0) {
            my $line = $str ? $str . substr($buf, 0, $idx + 1, '')
                            : substr($buf, 0, $idx + 1, '');

            $str = $buf;
            $potential_data_in_str = 1;
            return $line;
        } else {
            $str .= $buf;
        }
    }
}