46045-syslab/combinations/heartbeat_server.py

32 lines
1001 B
Python

import zmq
from xmlrpc.server import SimpleXMLRPCServer
# Other connect on the server port.
heartbeat_server_port = 10001
heartbeat_publish_port = 10002
# Make a context which we use to make sockets from
context = zmq.Context()
# Make a new socket. We want to publish on this socket.
socket = context.socket(zmq.PUB)
# Bind the socket (inside our program) to a port (on our machine)
# We can now send messages
socket.bind(f"tcp://*:{heartbeat_publish_port}")
# Make a function for others to call letting us know they are alive.
def send_heartbeat(sender: str):
print(f"Received heartbeat from {sender}")
# Publish who is alive now
socket.send_string(f"HEARTBEAT;{sender}")
# Return something just to show we succeeded
return 0
# Make an RPC server to serve that function to others
server = SimpleXMLRPCServer(('localhost', heartbeat_server_port))
# Register the function
server.register_function(send_heartbeat, 'send_heartbeat')
# Start up the server
server.serve_forever()