Answer to Question #227399 in Python for EpicHalzin

Question #227399

#using python3

# The client Sends All Data to server and then Closes the Connection,

#without expecting reply.

# Using UDP datagrams for communication, then the protocol itself will

#deliver your data in discrete and identifiable chunks.

# Sending data over a stream but delimited as length-prefixed blocks.


import socket, struct

from argparse import ArgumentParser


header_struct = struct.Struct('!I') # messages up to 2**32 - 1 in length

def client(address):

   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

   sock.connect(address)

   sock.shutdown(socket.SHUT_RD)

   put_block(sock, b'Beautiful is better than ugly.')

   put_block(sock, b'Explicit is better than implicit.')

   put_block(sock, b'Simple is better than complex.')

   put_block(sock, b'')

   sock.close()


1
Expert's answer
2021-08-19T03:21:56-0400
import socket, struct
from argparse import ArgumentParser

header_struct = struct.Struct('!I')  # messages up to 2**32 - 1 in length

def recvall(sock, length):
    blocks = []
    while length:
        block = sock.recv(length)
        if not block:
            raise EOFError('socket closed with %d bytes left'
                           ' in this block'.format(length))
        length -= len(block)
        blocks.append(block)
    return b''.join(blocks)

def get_block(sock):
    data = recvall(sock, header_struct.size)
    (block_length,) = header_struct.unpack(data)
    return recvall(sock, block_length)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS