I'm at the point in my network learning where I have just realized things aren't perfect and network packets can get out of sync and might not send everything in one packet.
My program works for small data that is being sent over the socket, but not a large file. I keep getting ValueError: Expecting ','
or Expecting ':'
whenever trying to send a big file and I think it's because my receiving function is not that good. I've read up a lot on how you have to implement your own protocol for reading information from a socket but I still have found no information on how actually to implement that.
My program serializes some information on a computer and sends that over JSON to another computer. I heard somewhere that JSON automatically deals with sending packet information or something like that, but I'm not too clear about what that meant.
In any case, this is my receiving function:
def recieve(node, s, timeout=2):
s.setblocking(False)
#array of all data
all_data = []
begin = time.time()
while True:
#If data was received, break after timeout
if all_data and time.time()-begin > timeout:
break
#If no data received at all, wait some more
elif time.time() - begin > timeout * 2:
break
try:
data = ''
while len(data) < BUFFER_SIZE:
data += s.recv(BUFFER_SIZE - len(data))
if data:
all_data.append(data.decode('utf-8'))
#Reset begin for timeout
begin = time.time()
except:
pass
return json.loads(''.join(all_data))
And I just use `sendall(dumps((data1, data2, data3, data4, data5)).encode()) to encode my python information (which could be dictionaries, lists, etc).
I'm not sure if my timeouts even make any sense, I'm a complete beginner to network programming, and I'm not sure where to go from here. Should I use socket.makefile()
? Do I still need to implement a network protocol when using JSON? How do I implement a network wrapper system if I need it?
Thanks so much in advance!