Skip to content

Instantly share code, notes, and snippets.

@tsonglew
Created July 6, 2021 08:53
Show Gist options
  • Save tsonglew/b9165e8b40f58df6e5937717ab099baa to your computer and use it in GitHub Desktop.
Save tsonglew/b9165e8b40f58df6e5937717ab099baa to your computer and use it in GitHub Desktop.
python ipc demo
import argparse
import json
import sys
import time
from multiprocessing.connection import Client, Listener
parser = argparse.ArgumentParser()
parser.add_argument("--type", type=str)
args = parser.parse_args()
def listener():
address = ("localhost", 6000) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b"secret password")
conn = listener.accept()
print("connection accepted from", listener.last_accepted)
while True:
msg = conn.recv()
# do something with msg
if msg == "close":
conn.close()
break
data = msg
print("delay: ", time.time() * 1000 - data["ts"])
listener.close()
def client():
address = ("localhost", 6000)
conn = Client(address, authkey=b"secret password")
s = "a" * 1024 * 1024 * 1
print("size: ", sys.getsizeof(s))
data = {"ts": time.time() * 1000, "payload": s}
conn.send(data)
conn.send("close")
# can also send arbitrary objects:
# conn.send(['a', 2.5, None, int, sum])
conn.close()
if __name__ == "__main__":
print(args.type)
if args.type == "client":
client()
elif args.type == "listener":
listener()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment