我正在尝试在 python3.3 中实现一个服务器,该服务器预加载了一个单独的线程来对传入连接进行所有处理。
from multiprocessing import Process, Pipe, Queue
from multiprocessing.reduction import reduce_socket
import time
import socketserver,socket
def process(q):
while 1:
fn,args = q.get()
conn = fn(*args)
while conn.recv(1, socket.MSG_PEEK):
buf = conn.recv(100)
if not buf: break
conn.send(b"Got it: ")
conn.send(buf)
conn.close()
class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
print("Opening connection")
print("Processing")
self.server.q.put(reduce_socket(self.request))
while self.request.recv(1, socket.MSG_PEEK):
time.sleep(1)
print("Closing connection")
class MyServer(socketserver.ForkingTCPServer):
p = Process
q = Queue()
parent_conn,child_conn = Pipe()
def __init__(self,server_address,handler):
socketserver.ForkingTCPServer.__init__(self,server_address, handler)
self.p = Process(target=process,args=(self.q,))
self.p.start()
def __del__(self):
self.p.join()
server_address = ('',9999)
myserver = MyServer(server_address,MyHandler)
myserver.serve_forever()
我可以使用以下脚本测试它是否有效:
from multiprocessing.reduction import reduce_socket
import time
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 9999))
time.sleep(1)
print("reduce_socket(s)")
fn,args = reduce_socket(s)
time.sleep(1)
print("rebuild_socket(s)")
conn = fn(*args)
time.sleep(1)
print("using_socket(s)")
conn.send("poks")
print conn.recv(255)
conn.send("poks")
print conn.recv(255)
conn.send("")
print conn.recv(255)
conn.close()
不幸的是,似乎有什么问题,因为在运行测试 n 次后,我的 tmp 文件夹中充满了子文件夹:
$ ls /tmp/pymp*|wc -l
32000
这些临时文件由socket_reduce()
. 有趣的rebuild/reduce_socket()
是,客户端也创建了临时文件,但是一旦函数退出,它们就会被删除。我当前的 tmp 文件系统中的最大文件夹数量是 32000,这会导致问题。我可以手动或在服务器的某个地方删除 /tmp/pymp* 文件,但我想也应该有正确的方法来执行此操作。谁能帮我这个?