所以我使用socket.connec
连接到IRC聊天我通过socket.send
传递我的变量登录登录成功,然后我坐在一个真正的循环使用 Socket.recv(1024)
如果我只是不断打印响应,一切看起来都很好,但是我想说我想添加到字符串的末尾......我注意到socket.recv并不总是得到完整的消息(仅按预期捕获最多1024个),消息的其余部分在循环的下一次迭代中。
这使得无法逐行处理反馈。
是否有更好的方法可以在不中断数据的情况下不断读取数据?是否有可能在接收响应之前确定响应的大小,以便可以动态设置缓冲区?
答案 0 :(得分:0)
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'