Python: make sure to send 1024 bytes at a time
<p>perl_server.pl  </p>

<pre><code>$client_socket = $socket-&gt;accept();

if (defined $client_socket) {
    $client_socket-&gt;autoflush(1);
    $client_socket-&gt;setsockopt(SOL_SOCKET, SO_RCVTIMEO, pack('l!l!', 30, 0)) or die "setsockopt: $!";
}

    while (1) {
        my $line = "";
        $client_socket-&gt;recv($line, 1024);
        print "$line\n";
}
</code></pre>

<p>python_client.py  </p>

<pre><code>def random_line():
    return "random len of line here"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (brock_host, int(brock_port))
sock.connect(server_address)
while True:
    sock.sendall(random_line())
</code></pre>

<p>How do i gurantee so that perl_server receives line at a time (not mangled)?<br>
Or prevent line from being buffered so it's not printing in the server side unless another line comes in?</p>

<p>i believe if i make sure the size of the item sent is 1024, then perl server would get a line at a time, correct?</p>

<p>How do i make sure if the line is 1024 bytes at a time?</p>

<p>whats a good strategy if the line is longer than 1024 bytes? (not sure if this is a case to be concerned about)</p>

<p>normally, a line would be somewhere around 50 characters</p>

<p>Maybe a combination of using stride, length, and padding. <code>max</code> isn't needed as you are sure the slice is smaller than your packet size.</p>

<pre><code>M = 32

for length in (M - 1, M, M + 1):

    payload = '1' * length

    for i in range(0, len(payload), M):

        packet = payload[i : i + M]

        packet += '0' * (M - len(packet))

        print(packet)

print()
</code></pre>

<p>Output:</p>

<pre><code>11111111111111111111111111111110

11111111111111111111111111111111

11111111111111111111111111111111
10000000000000000000000000000000
</code></pre>

python python-2.7 sockets