socket recv_into receiving incomplete

problem:

socket communication, the communication process is to send the message length, and then send the message content.

Problem is, client received ConnectionResetError:. [Errno 104] Connection reset by peer because the service receives incomplete end recv_into reported abnormal disconnected.

The reason: It may be tcp package sticky problem

 

 

The original server code:

import socket
from struct import pack, unpack

sck = socket.create_connection(ADDRESS)
sck.setblocking(True)
resp = bytearray(4)
if sck.recv_into(resp, 4) != 4:
    raise

rlen = unpack('>i', resp)[0]
resp = bytearray(rlen)
sck.settimeout(1)
recv_len = sck.recv_into(resp, rlen)
if recv_len != rlen:
    raise

if PY3:
    resp = resp.decode('utf-8')
else:
    resp = bytes(resp)

 

The revised service-side code:

sck.setblocking(True)
resp = bytearray(4)
if sck.recv_into(resp, 4) != 4:
    raise 

rlen = unpack('>i', resp)[0]
resp = bytearray(rlen)
view = memoryview(resp)
sck.settimeout(1)
while rlen > 0:
    nbytes = sck.recv_into(view, rlen)
    if nbytes == 0:
        raise 
    view = view[nbytes:]
    rlen -= nbytes

if PY3:
    resp = resp.decode('utf-8')
else:
    resp = bytes(resp)

 

ref: https://stackoverflow.com/questions/15962119/using-bytearray-with-socket-recv-into

Reproduced in: https: //my.oschina.net/sukai/blog/3057798

Guess you like

Origin blog.csdn.net/weixin_34367845/article/details/91706833