I'm currently writing a python script which needs some simple networking. After some playing around with sockets, this emerged, but as this is my first foray into sockets I'd really like a second opinion.
Edit: I know my script is not PEP8 compliant, as this is just an experiment. I posted it here to get Feedback about my usage of Sockets, and if there are any pitfalls or corner cases I overlooked.
Package Format:
datalength+1 \0 data \0
import socket
sep: bytes = b'\0'
minpacketsize: int = 10
def sendpacket(sock: socket.socket, data: bytes) -> None:
send: bytes = str(len(data) + 1).encode('utf-8') + sep + data + sep
if len(send) < minpacketsize:
raise ValueError("Packet too small!")
sock.sendall(send)
def recivepacket(sock: socket.socket) -> bytes:
datalen = 0
header: bytearray = bytearray()
while not datalen:
header += sock.recv(1)
if header.endswith(sep):
try:
datalen = int(header[:-1].decode('utf-8'))
except UnicodeDecodeError or ValueError as e:
raise ValueError("Error while decoding header!") from e
if len(header) == 10:
raise ValueError("Could not find Header!")
rawdata: bytes = sock.recv(datalen)
if rawdata.endswith(sep):
return rawdata[:-1]
else:
raise ValueError("Could not find Packet end!")