gpt4 book ai didi

python - 如何使用 socketserver 接收大文件?

转载 作者:可可西里 更新时间:2023-11-01 10:35:22 27 4
gpt4 key购买 nike

服务器端为客户端接收和发回数据:

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()))

但是在最后一 block 数据之后实现这个“挂起”。我的问题是,需要更改什么才能获取所有数据。

最佳答案

我在前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()))

关于python - 如何使用 socketserver 接收大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com