IHMO 这最好使用异步 I/O 库/框架来完成。这是一个使用这样的解决方案circuits https://github.com/circuits/circuits:
服务器将收到的内容回显到标准输出,客户端打开一个文件并将其发送到服务器,等待它完成,然后关闭套接字并终止。这是通过异步 I/O 和协程的混合来完成的。
服务器.py:
from circuits import Component
from circuits.net.sockets import UNIXServer
class Server(Component):
def init(self, path):
UNIXServer(path).register(self)
def read(self, sock, data):
print(data)
Server("/tmp/server.sock").run()
客户端.py:
import sys
from circuits import Component, Event
from circuits.net.sockets import UNIXClient
from circuits.net.events import connect, close, write
class done(Event):
"""done Event"""
class sendfile(Event):
"""sendfile Event"""
class Client(Component):
def init(self, path, filename, bufsize=8192):
self.path = path
self.filename = filename
self.bufsize = bufsize
UNIXClient().register(self)
def ready(self, *args):
self.fire(connect(self.path))
def connected(self, *args):
self.fire(sendfile(self.filename, bufsize=self.bufsize))
def done(self):
raise SystemExit(0)
def sendfile(self, filename, bufsize=8192):
with open(filename, "r") as f:
while True:
try:
yield self.call(write(f.read(bufsize)))
except EOFError:
break
finally:
self.fire(close())
self.fire(done())
Client(*sys.argv[1:]).run()
在我对此的测试中,它的行为完全符合我的预期,没有
错误,服务器在客户端关闭之前获取完整的文件
插座并关闭。