Reputation: 360
I'm building a p2p network and each process represents a peer. I'm using RPC for peer-to-peer communication. Each process (peer) needs to be able to receive messages from other peers and also send out messages. I already have a pretty simple server and client toy projects running.
server.py:
cache = []
def updateCache(elem):
cache.append(elem)
print(cache)
return "message updated"
server = SimpleXMLRPCServer(("localhost", 6789))
server.register_function(updateCache, "updateCache")
server.serve_forever()
client.py:
proxy.updateCache(f'message is: {sys.argv[1]}')
My question is, how do I combine the two so that one process can do both? What would be the best way to do this in python? Thank you!
Upvotes: 0
Views: 560
Reputation: 44108
Per the comment of @furas:
def server():
from xmlrpc.server import SimpleXMLRPCServer
cache = []
def updateCache(elem):
cache.append(elem)
print(cache)
return "message updated"
with SimpleXMLRPCServer(('localhost', 6789)) as server:
server.register_function(updateCache, "updateCache")
server.serve_forever()
def client(msg):
from xmlrpc.client import ServerProxy
proxy = ServerProxy('http://localhost:6789')
print(proxy.updateCache(f'message is: {msg}'))
if __name__ == '__main__':
from threading import Thread
import sys
# The server will end as soon as the main thread ends:
Thread(target=server, daemon=True).start()
client(sys.argv[1])
python test.py Booboo
Prints:
['message is: Booboo']
127.0.0.1 - - [16/Oct/2022 09:03:53] "POST /RPC2 HTTP/1.1" 200 -
message updated
Upvotes: 1