【发布时间】:2019-06-23 20:08:48
【问题描述】:
我有两个 Python 脚本,一个 TCP 服务器发送数据(以每秒 1/256 次的速率)和一个 TCP 客户端接收数据。在客户端脚本中,我打印接收到的数据的长度。 我从服务器发送了字符串“5.8”(因此数据长度为 3)。
当客户端和服务器在同一台机器上时: 接收到的数据长度始终为 3。 当客户端和服务器位于同一本地网络中的不同机器上时: 数据长度不同,但在 39 左右(发送数据的 13 倍)。
对于这种差异是否有可能的解释?
我认为增加这么多延迟的网络不太可能,因为命令行“ping”最多可以打印 2 毫秒的延迟和最大的数据量。
重要提示:我使用的是 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()
【问题讨论】:
-
您服务器的数据被 TCP 中的“Nagle 算法”延迟和缓冲在连接的发送端。有关详细信息,请参阅en.wikipedia.org/wiki/Nagle%27s_algorithm,有关在 Python 中发送时抑制 Nagle 的方法,请参阅 stackoverflow.com/questions/31826762/…。不管 Nagle 是什么,即使在本地连接上发送时,正如@maxim-egorushkin 所说,TCP 总是有可能接收与发送方写入大小不同的数据块。您的程序必须准备好应对这种情况。
标签: python networking tcp