불완전 수신 recv_into 소켓

문제 :

소켓 통신, 통신 프로세스는 메시지의 길이를 전송하고 메시지 내용을 전송하는 것입니다.

서비스가 끊긴 이상보고 recv_into 불완전 단부를 수신하기 때문에 문제는, 클라이언트가 피어 :. [ERRNO 104] 연결 재설정 ConnectionResetError 수신된다.

이유 : 그것은 TCP 패킷 끈적 문제가있을 수 있습니다

 

 

원래 서버 코드 :

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)

 

개정 된 서비스 측 코드 :

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

HTTPS : //my.oschina.net/sukai/blog/3057798 재현

추천

출처blog.csdn.net/weixin_34367845/article/details/91706833