场景描述:
客户端读取一个文件的每一行
与服务端建立scoket链接
服务端接收客户端发送的数据
服务端将文件写到本地
客户端代码:
import socket import time obj = socket.socket() obj.connect(("192.168.169.133",8080)) ret_bytes = obj.recv(1024) ret_str = str(ret_bytes,encoding="utf-8") #print(ret_str) filename ="d:/part-r-00000.txt" while True: inp ="" if inp == "q": obj.sendall(bytes(inp,encoding="utf-8")) break else: for line in open(filename): time.sleep(1/20) inp = line obj.sendall(bytes(inp, encoding="utf-8")) ret_bytes = obj.recv(1024) ret_str = str(ret_bytes,encoding="utf-8") print(ret_str)
服务端代码:
import socketserver #服务端 class Myserver(socketserver.BaseRequestHandler): def handle(self): f=open('f.txt','a') conn = self.request conn.sendall(bytes("你好,我是机器人",encoding="utf-8")) while True: ret_bytes = conn.recv(1024) ret_str = str(ret_bytes,encoding="utf-8") f.write(ret_str) f.write('\n') if ret_str == "q": break conn.sendall(bytes(ret_str+"你好我好大家好",encoding="utf-8")) f.close() if __name__ == "__main__": server = socketserver.ThreadingTCPServer(("192.168.169.133",8080),Myserver) server.serve_forever()