我意识到您的编辑正在澄清您想要的是实现目标的内置方法。但我不知道有任何东西可以帮助您对 readline 方法进行细粒度控制。但我想我可能只包括一个使用生成器和拆分进行编码方法的示例......只是为了好玩。
参考这个其他问题/答案以获得读取行的漂亮生成器:
https ://stackoverflow.com/a/822788/496445
基于该读者:
服务器.py
import socket
MAXLINE = 100
def linesplit(sock, maxline=0):
buf = sock.recv(16)
done = False
while not done:
# mid line check
if maxline and len(buf) > maxline:
yield buf, True
if "\n" in buf:
(line, buf) = buf.split("\n", 1)
err = maxline and len(line) > maxline
yield line+"\n", err
else:
more = sock.recv(16)
if not more:
done = True
else:
buf = buf+more
if buf:
err = maxline and len(buf) > maxline
yield buf, err
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
for line, err in linesplit(conn, MAXLINE):
if err:
print "Error: Line greater than allowed length %d (got %d)" \
% (MAXLINE, len(line))
break
else:
print "Received data:", line.strip()
conn.close()
客户端.py
import socket
import time
import random
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
val = 'x'*random.randint(1, 50)
if random.random() > .5:
val += "\n"
s.sendall(val)
time.sleep(.1)
s.close()
输出
Connected by ('127.0.0.1', 57912)
Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxx
Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
...
Received data: xxxxxxxxxxx
Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Error: Line greater than allowed length 100 (got 102)
服务器读取它接收到的数据,并在组装后不断检查行的长度。如果在任何时候该行超过指定的数量,它会返回一个错误代码。我把它放在一起的速度很快,所以我确信可以进一步清理检查,并且可以更改读取缓冲区的数量,以解决您希望在消耗过多数据之前检测长行的速度。在上面的输出示例中,我只得到了比允许的多 2 个字节,并且它停止了。
客户端只是发送随机长度的数据,换行的 50/50 变化。