TCP是基於流的協議。緩衝接收到的字節並僅從流中提取完整的消息。
有關完整行,請在緩衝區中查找換行符。
例服務器:
import socket
class Client:
def __init__(self,socket):
self.socket = socket
self.buffer = b''
def getline(self):
# if there is no complete line in buffer,
# add to buffer until there is one.
while b'\n' not in self.buffer:
data = self.socket.recv(1024)
if not data:
# socket was closed
return ''
self.buffer += data
# break the buffer on the first newline.
# note: partition(n) return "left of n","n","right of n"
line,newline,self.buffer = self.buffer.partition(b'\n')
return line + newline
srv = socket.socket()
srv.bind(('',5000))
srv.listen(1)
conn,where = srv.accept()
client = Client(conn)
print(f'Client connected on {where}')
while True:
line = client.getline()
if not line:
break
print(line)
實施例的客戶端:
s=socket()
s.connect(('127.0.0.1',5000))
s.sendall(b'line one\nline two\nline three\nincomplete')
s.close()
在服務器輸出:
Client connected on ('127.0.0.1', 2667)
b'line one\n'
b'line two\n'
b'line three\n'
試圖檢查每一行,看它是否與結束\ n或結尾\ r或以\ r \ n結尾,但沒有任何一行是。即使是完整的。在解碼utf-8之前和之後嘗試檢查。我想知道是否我的.splitlines()方法正在消除換行符 –
@AntonioAnonymous是的,'.splitlines()'移除了換行符。你必須緩衝,直到你有一個換行符,然後處理緩衝區。我會用一個例子來更新。 –