python - How to recv large files using socketserver? -
server side recv , send data client:
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 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 keyboard interrupt.')
client side read txt file, send server , wait reply:
def send_msg(data): import socket host = 'localhost' port = 50007 reply = '' try: socket.socket(socket.af_inet, socket.sock_stream) s: s.connect((host, port)) s.sendall(data) while true: data = s.recv(4096) if not data: break reply = reply+data.decode() except oserror err: reply = err finally: return reply #some.txt big txt file open(r'some.txt', 'rb') of: print(send_msg(of.read()))
but realization of "hang" after last chunk of data. question is, needs change, of data.
i solved problem follows in first 10 characters i'm sending data size receive , server-side checks received data, if sent client less, continue receive data.
so need modify server side:
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 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 keyboard interrupt.')
client side:
def send_msg(data): import socket host = 'localhost' port = 50007 reply = '' try: socket.socket(socket.af_inet, socket.sock_stream) 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 err: reply = err finally: return reply #some.txt big txt file open(r'some.txt', 'rb') of: print(send_msg(of.read()))
Comments
Post a Comment