TCP套接字无法在burs中发送消息

2024-09-29 05:16:21 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有多个系统通过消息通信使用TCP连接。你知道吗

我的send函数如下所示

def _send(self, message, dest):

    self.sendLock.acquire()
    message = pickle.dumps(message)
    #sending length
    message_length = len(message)
    self.outChan[dest].send('<MESSAGELENGTH>%s</MESSAGELENGTH>'
                            % str(message_length))

    for message_i in range(0, message_length, 1024):
        self.outChan[dest].send(message[:1024])
        message = message[1024:]

    self.sendLock.release()

接收线程如下所示:

def readlines(self, sock):

    while True:

        msg = ''

        opTag = '<MESSAGELENGTH>'
        clTag = '</MESSAGELENGTH>'

        while not all(tag in msg for tag in (opTag, clTag)):
            msg = sock.recv(1024)

        msglen = int(msg.split(clTag)[0].split(opTag)[1])
        msg = msg.split(clTag)[1]

        while len(msg) < msglen:
            msg += sock.recv(msglen-len(msg))

        self.rec.put(pickle.loads(msg))

从中读取消息后自我记录将向发件人发送确认消息。你知道吗

我已经实现了自己的缓冲区来控制网络中的流量。在任何时候,我都会发送atmost MAX\u BUFFER\u大小的消息,但没有收到确认。你知道吗

问题是:当程序启动时,它发送最大缓冲区大小的消息而不等待确认。但只有少数这些最大缓冲区大小的消息被接收。你知道吗

在其中一个最大缓冲区大小为5的模拟中,总共发送了100条消息,没有收到m2、m3和m4。所有其他消息都已收到(按发送顺序)。你知道吗

我怀疑错误是在最初的发送突发,但我无法找出确切的问题。你知道吗


Tags: inselfsend消息messagelenmsglength
1条回答
网友
1楼 · 发布于 2024-09-29 05:16:21

接收线程中有几个错误:

  1. 在检查接收到的消息的开始和结束标记时,您不是附加到已接收的部分,而是覆盖它。

  2. 检测到消息长度后,您将丢失后续消息,这些消息的结束标记已被接收,但尚未分析。

  3. 您可能正在将多条消息放在self.rec中。

这是一份更正后的表格,附有解释更改的注释:

def readlines(self, sock):

    msg = '' # initialize outside since otherwise remiander of previous message would be lost

    opTag = '<MESSAGELENGTH>' # no need to repeat this in each iteration
    clTag = '</MESSAGELENGTH>' # no need to repeat this in each iteration

    while True:

        while not all(tag in msg for tag in (opTag, clTag)):
            msg += sock.recv(1024) # += rather than =

        msglen = int(msg.split(clTag)[0].split(opTag)[1])
        msg = msg.split(clTag, 1)[1] # split just once, starting from the left

        while len(msg) < msglen:
            msg += sock.recv(msglen-len(msg))

        self.rec.put(pickle.loads(msg[:maglen])) # handle just one message
        msg = msg[msglen:] # prepare for handling future messages

相关问题 更多 >