服务器端recv和发回客户端的数据:
import socketserver class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): try: data = b'' while True: package = self.request.recv(4096) if not package: break data = data + package self.request.sendall(data) except ConnectionError as conError: print(conError) class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = "localhost", 50007 print('Server start work!') server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address try: server.serve_forever() except KeyboardInterrupt: print('Server stop by Keyboard Interrupt.')
客户端读取txt文件,发送给服务器并等待回复:
def send_msg(data): import socket HOST = 'localhost' PORT = 50007 reply = '' try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(data) while True: data = s.recv(4096) if not data: break reply = reply+data.decode() except OSError as err: reply = err finally: return reply #some.txt is big txt file with open(r'some.txt', 'rb') as of: print(send_msg(of.read()))
但是在最后一块数据之后实现了这个“挂起”。 我的问题是,什么需要改变,那将获得所有的数据。
我在发送数据大小的前10个字符中解决了以下问题,服务器端检查接收的数据,如果客户端发送的数据少,则继续接收数据。
所以你需要修改服务器端:
import socketserver class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): try: package = self.request.recv(4096) data_size = package[:10].strip(b'0') data = package[10:] while len(data) < int(data_size): package = self.request.recv(4096) if not package: break data = data + package self.request.sendall(data) except ConnectionError as conError: print(conError) class ThreadedTCPserver(socketserver.ThreadingMixIn, socketserver.TCPserver): pass if __name__ == "__main__": HOST, PORT = "localhost", 50007 print('server start work!') server = ThreadedTCPserver((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address try: server.serve_forever() except KeyboardInterrupt: print('server stop by Keyboard Interrupt.')
客户端:
def send_msg(data): import socket HOST = 'localhost' PORT = 50007 reply = '' try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(str(len(data)).encode().zfill(10)+data) while True: data = s.recv(4096) if not data: break reply = reply+data.decode() except OSError as err: reply = err finally: return reply #some.txt is big txt file with open(r'some.txt', 'rb') as of: print(send_msg(of.read()))