TCP 是一种字节流协议。没有消息,只有一堆字节传入。您必须实现一个协议并缓冲接收到的数据,直到您知道收到了完整的消息。
您可以使用内置的socket.makefile()
方法来实现面向线路的协议。例子:
服务器.py
from socket import *
s = socket()
s.bind(('',5000))
s.listen(1)
while True:
c,a = s.accept()
print(f'connect: {a}')
read = c.makefile('r')
write = c.makefile('w')
with c,read,write:
while True:
data = read.readline()
if not data: break
cmd = data.strip()
print(f'cmd: {cmd}')
if cmd == 'LIST':
write.write('C1\nC2\nC3\nDONE\n')
write.flush()
print(f'disconnect: {a}')
客户端.py
from socket import *
s = socket()
s.connect(('localhost',5000))
read = s.makefile('r',)
write = s.makefile('w')
def send(cmd):
print(cmd)
write.write(cmd + '\n')
write.flush()
with s,read,write:
send('TEST')
send('LIST')
while True:
data = read.readline()
if not data: break
item = data.strip()
if item == 'DONE': break
print(f'item: {item}')
send('OTHER')
服务器输出:
connect: ('127.0.0.1', 13338)
cmd: TEST
cmd: LIST
cmd: OTHER
disconnect: ('127.0.0.1', 13338)
客户端输出:
TEST
LIST
item: C1
item: C2
item: C3
OTHER