TCP 套接字不按顺序读取 [英] TCP socket reads out of turn

查看:59
本文介绍了TCP 套接字不按顺序读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 TCP 和 Python 套接字,将数据从一台计算机传输到另一台计算机.但是,recv 命令在服务器端读取的内容超出了它应有的内容,我找不到问题.

I am using TCP with Python sockets, transfering data from one computer to another. However the recv command reads more than it should in the serverside, I could not find the issue.

client.py

while rval:
    image_string = frame.tostring()
    sock.sendall(image_string)
    rval, frame = vc.read()

server.py

while True:
    image_string = ""
    while len(image_string) < message_size:
        data = conn.recv(message_size)
        image_string += data

消息的长度是 921600 (message_size) 所以它是用 sendall 发送的,但是当收到时,当我打印到达消息的长度时,长度有时是错误的,有时是正确的.

The length of the message is 921600 (message_size) so it is sent with sendall, however when recieved, when I print the length of the arrived messages, the lengths are sometimes wrong, and sometimes correct.

921600
921600
921923 # wrong
922601 # wrong
921682 # wrong
921600
921600
921780 # wrong

如您所见,错误的到达没有规律.当我使用 TCP 时,我希望有更多的一致性,但是似乎缓冲区混淆了,并且以某种方式接收了下一条消息的一部分,因此产生了更长的消息.这里有什么问题?

As you see, the wrong arrivals have no pattern. As I use TCP, I expected more consistency, however it seems the buffers are mixed up and somehow recieving a part of the next message, therefore producing a longer message. What is the issue here ?

我尝试只添加代码的相关部分,如果您愿意,我可以添加更多,但是代码在 localhost 上表现良好,但在两台计算机上失败,因此除了错误之外应该没有错误传输部分.

I tried to add just the relevant part of the code, I can add more if you wish, but the code performs well on localhost but fails on two computers, so there should be no errors besides the transmitting part.

Edit1:我检查了这个问题 有点,它提到客户端中的所有发送命令可能不会被服务器中的单个 recv 接收到,但我不明白如何将其应用到实践中.

I inspected this question a bit, it mentions that all send commands in the client may not be recieved by a single recv in the server, but I could not understand how to apply this to practice.

推荐答案

TCP 是一种流协议.您发送的数据块的大小与您接收的数据块的大小之间绝对没有联系.如果您想接收已知大小的数据,完全取决于您只请求那么多数据:您当前每次都请求数据的总长度,这将尝试读取太多,除非不太可能第一次 .recv() 调用检索整个数据的事件.基本上,您需要执行类似 data = conn.recv(message_size - len(image_string)) 的操作,以反映剩余数据量正在减少的事实.

TCP is a stream protocol. There is ABSOLUTELY NO CONNECTION between the sizes of the chunks of data you send, and the chunks of data you receive. If you want to receive data of a known size, it's entirely up to you to only request that much data: you're currently requesting the total length of the data each time, which is going to try to read too much except in the unlikely event of the entire data being retrieved by the first .recv() call. Basically, you need to do something like data = conn.recv(message_size - len(image_string)) to reflect the fact that the amount of remaining data is decreasing.

这篇关于TCP 套接字不按顺序读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆