【问题标题】:struct.error: repeat count given without format specifierstruct.error:没有格式说明符的重复计数
【发布时间】:2018-03-23 09:33:54
【问题描述】:

详情

我正在尝试了解实现选择性重复 (SR) 协议的网络程序。流程如下:

  1. 通过指定端口号、协议和窗口大小运行 server.py
  2. 通过指定文件名、端口号和数据包数运行 client.py

当我运行 client.py, 我收到这个错误:

Traceback (most recent call last):
File "client.py", line 238, in <module>
cs = pack('IHH' + str(len(data)), 's', seqNum, header, data)
struct.error: repeat count given without format specifier

这是让我感到困惑的代码块:

while not sendComplete:
    toSend = lastInWindow + 1
    data = GetMessage()
    header = int('0101010101010101', 2)
    cs = pack('IHH' + str(len(data)), 's', seqNum, header, data)
    checksum = CalculateChecksum(cs)

packet = pack('IHH' + str(len(data)) + 's', seqNum, checksum, header, data)
    if toSend < windowSize:
        sendBuffer.append(packet)
        timeoutTimers.append(TIMEOUT)
    else:
        sendBuffer[toSend % windowSize] = packet
        timeoutTimers[toSend % windowSize] = TIMEOUT

疑难解答

我已经采取了几个步骤来解决这个问题,但都失败了(很明显),我不确定我是更接近光线还是深入树林。

  1. 按照 PyCharm 的建议使用 struct.pack(fmt=...)
  2. 根据 PyCharm 的建议,我使用 + 连接参数
  3. 我再次运行程序并收到 TypeError: must be str, not int 错误,我尝试通过实现 str(seqNum)、str(header) 等来解决此错误。
  4. 最后,我得到一个 TypeError: pack() takes no keyword arguments 响应并认输。

如果有人能解释这里发生了什么以及如何启动和运行这个程序,我将不胜感激。

【问题讨论】:

    标签: python struct network-programming


    【解决方案1】:

    问题是你在pack格式函数上打错了,而不是(','而不是'+'):

    pack('IHH' + str(len(data))<strong>,</strong> 's', seqNum, header, data)

    应该是:

    pack('IHH' + str(len(data)) <strong>+</strong> 's', seqNum, header, data)

    发生这种情况是因为每次在字节格式中有一个数字时,它都会重复下一个字符数字次​​。所以4h 将变为hhhh。错误的行以数字结尾(例如:“IHH6”),所以它不知道要重复什么。

    另外,你要打包 4 个“东西”,你应该在 pack 函数中添加另一个参数:

    pack('IHH' + str(len(data)) + 's', seqNum, header, data, missing_var)
    

    【讨论】:

    • 太好了,谢谢。我做了以下更改:cs = pack('IH' + str(len(data)), 's', seqNum, header, data),我被告知“struct.error: 's' 的参数必须是一个字节对象”。我使用字节('s','utf-8)将其更改为字节,但后来我被告知它应该是一个str。我把它改成str('s'),然后它说's'必须是一个字节对象。为什么会这样来回走动?
    • 我无法重现您所说的错误,例如:repl.it/repls/BumpyMushyDaemons
    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多