I have two Python scripts, one TCP-server sending data (at a rate of 1/256 times a second) and a TCP-client receiving data. In the client script, I print the length of the received data. I sent the string "5.8" from the server (thus data of length 3).
When client and server are on the same machine: The length of data received is always 3. When client and server are on different machines in the same local network: The length of data differs but is around 39 (13 times the data sent).
Is there a possible explanation for this discrepancy?
I think the network adding this much latency is unlikely, because the command line "ping" prints at most 2 ms latency with the largest amount of data.
IMPORTANT: I'm using Python 2.7.
import socket
def server():
host = 'localhost' # replace with IP address in case client is on another machine
port = 5051
s = socket.socket()
s.bind((host, port))
s.listen(1)
client_socket, adress = s.accept()
while True:
client_socket.send('a'.encode())
client_socket.close()
if __name__ == '__main__':
server()
import socket, random, time
def client():
host = 'localhost' # replace with IP address in case client is on another machine
port = 5051
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_err = s.connect_ex((host, port))
print(s_err)
while True:
data = s.recv(2048)
print(len(data)) # returns different values depending on client location
s.close()
if __name__ == '__main__':
client()
This is what worked for me: I changed the buffer size of recv() to the number of bytes I want to receive, so in this case
data = s.recv(3)
instead of
data = s.recv(2048)
While on the local machine, something automatically decided that the data can be sent in the smallest packages, while this was not the case when using a local network. So I forced the size of the data sent.
This of course potentially leads to problems of lag. So elsewhere I need to make sure that the remaining data are emptied regularly with a large buffer size, or close the connection if not needed. Not sure about the last one, since I'm still a beginner.