heartbeat.py
48 lines
| 1.6 KiB
| text/x-python
|
PythonLexer
Brian Granger
|
r2910 | """The client and server for a basic ping-pong style heartbeat. | ||
""" | ||||
#----------------------------------------------------------------------------- | ||||
# Copyright (C) 2008-2010 The IPython Development Team | ||||
# | ||||
# Distributed under the terms of the BSD License. The full license is in | ||||
# the file COPYING, distributed as part of this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
MinRK
|
r4500 | import socket | ||
Brian Granger
|
r2910 | import sys | ||
from threading import Thread | ||||
import zmq | ||||
MinRK
|
r3144 | from IPython.utils.localinterfaces import LOCALHOST | ||
Brian Granger
|
r2910 | #----------------------------------------------------------------------------- | ||
# Code | ||||
#----------------------------------------------------------------------------- | ||||
class Heartbeat(Thread): | ||||
"A simple ping-pong style heartbeat that runs in a thread." | ||||
MinRK
|
r3144 | def __init__(self, context, addr=(LOCALHOST, 0)): | ||
Brian Granger
|
r2910 | Thread.__init__(self) | ||
self.context = context | ||||
MinRK
|
r5170 | self.ip, self.port = addr | ||
MinRK
|
r4500 | if self.port == 0: | ||
s = socket.socket() | ||||
MinRK
|
r5170 | # '*' means all interfaces to 0MQ, which is '' to socket.socket | ||
s.bind(('' if self.ip == '*' else self.ip, 0)) | ||||
MinRK
|
r4500 | self.port = s.getsockname()[1] | ||
s.close() | ||||
MinRK
|
r5170 | self.addr = (self.ip, self.port) | ||
Brian Granger
|
r2910 | self.daemon = True | ||
def run(self): | ||||
self.socket = self.context.socket(zmq.REP) | ||||
MinRK
|
r4500 | self.socket.bind('tcp://%s:%i' % self.addr) | ||
Brian Granger
|
r2910 | zmq.device(zmq.FORWARDER, self.socket, self.socket) | ||