前言
项目中总会遇到数据需要跨进程通信的问题,今天就给大家带来一套简单的跨进程通信代码。代码分为服务端与客户端两部分。
一、server端
import multiprocessing
import timedef do_socket(conn, addr, ):try:while True:if conn.poll(1) == False:time.sleep(0.5)continuedata = conn.recv() # 等待接受数据conn.send('sucess')# ***********************# 要执行的程序写在这里# ***********************print(data)except Exception as e:print('Socket Error', e)finally:try:conn.close()print('Connection close.', addr)except:print('close except')def run_server(host, port):from multiprocessing.connection import Listenerserver_sock = Listener((host, port))print("Sever running...", host, port)pool = multiprocessing.Pool(10)while True:# 接受一个新连接:conn = server_sock.accept()addr = server_sock.last_acceptedprint('Accept new connection', addr)# 创建进程来处理TCP连接:pool.apply_async(func=do_socket, args=(conn, addr,))if __name__ == '__main__':server_host = '127.0.0.1'server_port = 8000run_server(server_host, server_port)
二、client端
import timefrom multiprocessing.connection import Clientclient = Client(('127.0.0.1', 8000))while True:data = 'send data'client.send(data)data = client.recv() # 等待接受数据print(data)time.sleep(1)
这里只是给了client
端的示例代码,实际通信的数据类型可以是多样的(字符串、数字、图片等)
三、运行效果
先运行server端,再运行client端。server
端
client
端