It is impossible to process a data segment if the data in it does not end with the characters 0x0A 0x0D

The server looks like this:

$server = IO::Socket::INET->new(LocalPort => 7777, TYPE => SOCK_STREAM, Reuse => 1, Listen => SOMAXCONN, KeepAlive => 1, Timeout => 10) or die "Couldn't be a tcp server on port $server_port: $@\n"; while($client = $server->accept()) { defined(my $child_pid = fork()) or die "Can't fork new child $!"; if ($child_pid == 0) { close( $server ); } $client->autoflush( 1 ); while(my $buffer = <$client>) { print unpack("H*", $buffer); } } 

For clarity, printed hexadecimal presentation of the data segment. Printing of received data is triggered only if the data segment is terminated with the characters 0x0A 0x0D, or if the buffer is full, or if the client has disconnected.

In addition, you need to be able to print all accepted segments, even without 0A 0D at the end.

    1 answer 1

    The problem is here:

     while(my $buffer = <$client>) { 

    Instead of <> you need to use, for example, sysread .

    And by the way,

    As of VERSION 1.18 all IO :: Socket objects have autoflush turned on by default .

    Working example:

    server.pl

     #!/usr/bin/perl use Modern::Perl; use IO::Socket::INET; use Carp qw/confess/; use Const::Fast; const my $CHUNK_MAX => 1024; const my $SERVER_PORT => 7777; const my $SERVER_HOST => '127.0.0.1'; my $server = IO::Socket::INET->new( LocalPort => $SERVER_PORT, LocalHOST => $SERVER_HOST, TYPE => SOCK_STREAM, Reuse => 1, Listen => SOMAXCONN, KeepAlive => 1, Timeout => 10 ) or confess "Can not create server on $SERVER_HOST:$SERVER_PORT: $@"; while ( my $client = $server->accept() ) { while ( sysread( $client, my $buffer, $CHUNK_MAX ) ) { say $buffer. ' => ' . unpack( "H*", $buffer ); } } 

    client.pl

     #!/usr/bin/perl use Modern::Perl; use IO::Socket::INET; use Carp qw/confess/; use Const::Fast; const my $SERVER_PORT => 7777; const my $SERVER_HOST => '127.0.0.1'; my $sock = IO::Socket::INET->new("$SERVER_HOST:$SERVER_PORT") or confess "Can not connect to server on $SERVER_HOST:$SERVER_PORT: $@"; print $sock 'BADDCAFE'; sleep 10; print $sock 'DEADBEEF'; close($sock);