服务器端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()))
但是在最后一块数据之后实现这种“挂起”。我的问题是,需要改变什么才能获得所有数据。
答案 0 :(得分:1)
我在前10个字符中解决了问题,我发送数据大小以便接收,服务器端检查接收到的数据,如果客户端发送的数据较少,则继续接收数据。 / p>
所以你需要修改服务器端:
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()))