Python中multiprocessing.connection模块的用途及示例
发布时间:2023-12-27 06:53:56
multiprocessing.connection模块是Python中的一个用于多进程通信的模块。它提供了两种类型的连接:Client和Listener。Client用于与已有的服务端进程进行通信,而Listener用于创建一个新的服务端进程来接收客户端的请求。
使用multiprocessing.connection模块可以方便地在多进程之间传递数据,实现进程间的通信。下面是一个使用该模块的示例代码:
# 服务端程序
from multiprocessing.connection import Listener
def server():
address = ('localhost', 6000) # 服务端地址
with Listener(address) as listener:
conn = listener.accept() # 等待客户端连接
print('Connection accepted from', listener.last_accepted)
while True:
# 接收客户端发送的消息
msg = conn.recv()
if msg == 'close':
break
print('Received', msg)
# 将消息返回给客户端
conn.send(msg)
conn.close()
# 客户端程序
from multiprocessing.connection import Client
def client():
address = ('localhost', 6000) # 服务端地址
with Client(address) as conn:
# 发送消息给服务端
conn.send('Hello, server!')
# 接收服务端返回的消息
response = conn.recv()
print('Received from server:', response)
# 发送关闭连接的请求
conn.send('close')
if __name__ == '__main__':
# 启动服务端和客户端进程
server_process = Process(target=server)
server_process.start()
client_process = Process(target=client)
client_process.start()
# 等待进程结束
server_process.join()
client_process.join()
上述代码是一个简单的服务端和客户端程序,它们通过multiprocessing.connection模块进行通信。服务端使用Listener来监听指定的地址,并接受客户端连接。客户端使用Client来连接到服务端,并向服务端发送消息。服务端接收到客户端发送的消息后,将其返回给客户端。
在这个示例中,服务端和客户端在不同的进程中运行,它们通过进程间通信实现数据的传递和通信。multiprocessing.connection模块提供了方便的接口和方法来实现进程间的通信,使得多进程编程更加简单和灵活。
