如何冲洗Python套接字? [英] How do you flush Python sockets?

查看:79
本文介绍了如何冲洗Python套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用Python编写了一个服务器,旨在以"Header:Message"形式向客户端发送数据

I've written a server in Python that is meant to send data to the client in the form "Header:Message"

我希望能够分别发送每条消息,以便客户端只需执行最少的工作即可读取标头"和消息"

I would like to be able to have each message sent individually so that the client will need to perform minimal work in order to read the "header" and the "message"

不幸的是,我无法弄清楚如何正确地刷新python套接字,因此当我多次连续执行多个发送时,消息会在套接字缓冲区中集中在一起并作为一个大块发送.

Unfortunately, I can't figure out how to properly flush a python socket so when I have multiple sends execute in quick succession the messages get lumped together in the socket buffer and sent as one big chunk.

示例:

服务器发送...

socket.send ("header1:message1")
socket.send ("header2:message2")
socket.send ("header3:message3")

客户收到... "header1:message1header2:message2header3:message3"

Client receives... "header1:message1header2:message2header3:message3"

我想收到三封个人邮件

header1:message1
header2:message2
header3:message3

我需要一种在每次发送后刷新的方法

I need a way to flush after each send

推荐答案

我猜您正在通过TCP连接进行通信.

I guess you are talking over a TCP connection.

您的方法存在缺陷. TCP流定义为字节流.您始终必须使用某种分隔符,并且可能不依赖网络堆栈来分隔您的消息.

Your approach is flawed. A TCP stream is defined as a stream of bytes. You always have to use some sort of separator and may not rely on the network stack to separate your messages.

如果您确实需要基于数据报的服务,请切换到UDP.在这种情况下,您需要自己处理重传.

If you really need datagram based services switch to UDP. You'll need to handle retransmission yourself in that case.

要澄清:

刷新发送缓冲区通常会创建新的程序包,正如您所期望的那样.如果您的客户足够快地读取这些软件包,则每次读取可能会收到一条消息.

Flushing the send buffer usually creates new packages, just as you expect. If your client reads these packages fast enough you may get one message per read.

现在,假设您通过卫星链路进行通信.由于高带宽和高延迟,sat之前的最后一个路由器会等待一小段时间,直到缓冲区中有足够的数据,然后立即发送所有数据包.您的客户端现在将立即接收所有数据包,并将所有数据立即放入接收缓冲区.因此,您的分离又消失了.

Now imagine you communicate over a satellite link. Because of high bandwidth and latency, the last router before the sat waits a short time until enough data is in the buffer and sends all your packets at once. Your client will now receive all packets without delay and will put all the data in the receive buffer at once. So your separation is gone again.

这篇关于如何冲洗Python套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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