import multiprocessingimport multiprocessing.connectionimport threadingimport timeimport os#工作线程class ThreadWork:#conn: 连接生成的 Connection 对象def __init__(self, conn):self.conn = conn # Connection对象self.go = True # 线程退出标识#终止线程def terminate(self):self.go = False#线程函数def run(self):while self.go:try:x, y = self.conn.recv()except EOFError:breakexcept ConnectionResetError:breakexcept:breakresult = x + ytime.sleep(1)try:self.conn.send(result)except ConnectionResetError:breakexcept:break# 关闭连接self.conn.close()def main():#创建服务器serv = multiprocessing.connection.Listener(("", 15000), backlog=2000, authkey=b"12345")print("pid =", os.getpid())print("server is running{} ...".format(serv.address))while True:try:# 获取连接,返回一个 Connection 对象conn = serv.accept()print("> {}{}".format(time.ctime(), serv.last_accepted))# 启动一个线程tw = ThreadWork(conn)threading.Thread(target=tw.run, daemon=True).start()except multiprocessing.AuthenticationError as e: #身份验证失败print(e)except ConnectionResetError:passexcept:print("*** 发生严重错误 ***")passserv.close()if __name__ == "__main__":main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。