【问题标题】:python struct module (python 2.4)python结构模块(python 2.4)
【发布时间】:2014-03-21 19:11:23
【问题描述】:

我正在尝试通过 unix 域套接字向应用程序发送缓冲区,接收带有更新值的相同结构,然后将该缓冲区发送回该应用程序。我能够发送一个新打包的数据并接收回响应,但是如果我尝试打包接收到的缓冲区并通过套接字再次发送,我会遇到错误,说发送到应用程序的大小不匹配它正在侦听套接字并关闭套接字。

下面的片段是我想要实现的。看起来我用来发回数据的字节序/字符串转换不正确。

""" request struct
#structure i am sending over unix domain socket
struct prod_entry {
    unsigned int        Model;
    unsigned int        year;
    char                    prodname[64];
    }
"""


value = (1, 1992, "mustang")

我在这里做错了什么。我想接收一个缓冲包并再次发送。

prod_entry = struct.pack('I I 64s', *value)


def update(update_records):
    try:
        comm_sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
    except socket.error:
        return 


    try:
        comm_sock.connect(PROD_UNIX_DOMAIN_SKT)
    except socket.gaierror:
        return 

    try:
        comm_sock.sendall(update_records)
    except socket.error:
        return  

    reply = comm_sock.recv(struct.calcsize('I I 64s '))
    out1 = struct.unpack('<I I 64s',reply)

    rebound = struct.pack('I I 64s', *out1)
    comm_sock.sendall(rebound)

    reply2 = comm_sock.recv(struct.calcsize('I I 64s '))
    out2 = struct.unpack('<I I 64s',reply2)

    comm_sock.close()

update(prod_entry)

我收到 ::struct.error: unpack str size does not match format

【问题讨论】:

    标签: python


    【解决方案1】:

    recv bufsize 参数仅指定最大大小。 recv 可能会返回比最大指定大小更小的块。你需要遍历recv,以防它没有返回完整的打包字符串。

    您很快就会发现,您需要一个用于任何此类网络通信的协议。熟悉(例如)HTTP 协议,尤其是。 request methods

    【讨论】:

    • 是的,你是对的,对于 recv,我们指定了最大缓冲区大小,它不等于我试图解包的大小,因此我得到了那个错误。我通过打印 recv 返回的缓冲区大小找到了这一点,并相应地调整了我的解包格式。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多