重新发明轮子是没有意义的。通过使用以下命令将字符串作为 python 字符串对象发送,可以轻松发送可变长度字符串:multiprocessing.connection
模块。此方法将允许发送大多数 python 对象,而不仅仅是字符串。
import multiprocessing
import multiprocessing.connection as connection
def producer(data, address, authkey):
with connection.Listener(address, authkey=authkey) as listener:
with listener.accept() as conn:
print('connection accepted from', listener.last_accepted)
for item in data:
print("producer sending:", repr(item))
conn.send(item)
def consumer(address, authkey):
with connection.Client(address, authkey=authkey) as conn:
try:
while True:
item = conn.recv()
print("consumer received:", repr(item))
except EOFError:
pass
listen_address = "localhost", 50000
remote_address = "localhost", 50000
authkey = b'secret password'
if __name__ == "__main__":
data = ["1", "23", "456"]
p = multiprocessing.Process(target=producer, args=(data, listen_address, authkey))
p.start()
consumer(remote_address, authkey)
p.join()
print("done")
这会产生类似的结果:
producer sending: '1'
producer sending: '23'
consumer received: '1'
producer sending: '456'
consumer received: '23'
consumer received: '456'
done