python socket: sending and receiving 16 bytes - Stack Overflow

本文讨论了使用Python Socket进行数据块传输时遇到的问题,发送方发送的数据与接收方收到的数据长度不符,出现27字节的偏差。文章分析了可能的原因,并提出了改进措施。

 

python socket: sending and receiving 16 bytes - Stack Overflow

    python socket: sending and receiving 16 bytes
    up vote 3 down vote favorite
    3
       

    See edits below.

    I have two programs that communicate through sockets. I'm trying to send a block of data from one to the other. This has been working with some test data, but is failing with others.

    s.sendall('%16d' % len(data))
    s.sendall(data)
    print(len(data))

    sends to

    size = int(s.recv(16))
    recvd = ''
    while size > len(recvd):
        data = s.recv(1024)
        if not data:
            break
        recvd += data
    print(size, len(recvd))

    At one end:

    s = socket.socket()
    s.connect((server_ip, port))

    and the other:

    c = socket.socket()
    c.bind(('', port))
    c.listen(1)
    s,a = c.accept()

    In my latest test, I sent a 7973903 byte block and the receiver reports size as 7973930.

    Why is the data block received off by 27 bytes?

    Any other issues?

    Python 2.7 or 2.5.4 if that matters.

    EDIT: Aha - I'm probably reading past the end of the send buffer. If remaining bytes is less than 1024, I should only read the number of remaining bytes. Is there a standard technique for this sort of data transfer? I have the feeling I'm reinventing the wheel.

    EDIT2: I'm screwing up by reading the next file in the series. I'm sending file1 and the last block is 997 bytes. Then I send file2, so the recv(1024) at the end of file1 reads the first 27 bytes of file2.

    I'll start another question on how to do this better.

    Thanks everyone. Asking and reading comments helped me focus.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值