Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def get_random_port(min_port=49152, max_port=65536, max_tries=100):
"""
Return available random ZeroMQ port.
"""
ctx = zmq.Context()
sock = ctx.socket(zmq.REQ)
try:
port = sock.bind_to_random_port('tcp://*', min_port, max_port, max_tries)
except:
raise zmq.ZMQError(msg='Could not find free port')
finally:
sock.close()
return port
#
# Request-reply client in Python
# Connects REQ socket to tcp://localhost:5559
# Sends "Hello" to server, expects "World" back
#
import zmq
# Prepare our context and sockets
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
# Do 10 requests, waiting each time for a response
for request in range(1,10):
socket.send("Hello")
message = socket.recv()
print "Received reply ", request, "[", message, "]"
def __init__(self, protocol="tcp", host="localhost", port="80"):
url = "%s://%s:%s" % (protocol, host, port)
context = zmq.Context()
self.handler = context.socket(zmq.REQ)
self.handler.connect(url)
# default value
self.cf_str = u''
self.scf_str = u''
self.statistic = 0
self.period = 5
self.time_from = 0
self.time_to = 0
self.key = u''
async def connect_zmq():
context = Context.instance()
# Socket to talk to server
current_app.flowapi_logger.debug("Connecting to FlowMachine server…")
socket = context.socket(zmq.REQ)
socket.connect(
f"tcp://{current_app.config['FLOWMACHINE_HOST']}:{current_app.config['FLOWMACHINE_PORT']}"
)
request.socket = socket
current_app.flowapi_logger.debug("Connected.")
def connect_channels(self):
ports = self.ports
context = self.context
shell = context.socket(zmq.REQ)
shell.connect("tcp://127.0.0.1:{}".format(ports["shell_port"]))
shell.setsockopt(zmq.LINGER, 0)
stdin = context.socket(zmq.REQ)
stdin.connect("tcp://127.0.0.1:{}".format(ports["stdin_port"]))
stdin.setsockopt(zmq.LINGER, 0)
iopub = context.socket(zmq.SUB)
iopub.connect("tcp://127.0.0.1:{}".format(ports["iopub_port"]))
iopub.setsockopt(zmq.LINGER, 0)
iopub.setsockopt(zmq.SUBSCRIBE, b"")
control = context.socket(zmq.REQ)
control.connect("tcp://127.0.0.1:{}".format(ports["control_port"]))
control.setsockopt(zmq.LINGER, 0)
self.shell = shell
self.stdin = stdin
self.iopub = iopub
self.control = control
poller = zmq.Poller()
poller.register(rdp_ctl_socket,zmq.POLLIN)
while not self.shutdown_called:
poll_results = {fd: _flag for (fd, _flag) in poller.poll()}
if poll_results.get(rdp_ctl_socket) == zmq.POLLIN:
messages = recvall(rdp_ctl_socket)
if 'shutdown' in messages:
log.debug('shutdown message received in request_perform_dispatch')
return
elif 'task_avail' in messages:
log.debug('task available message received')
task_avail = True
while task_avail and not self.shutdown_called:
task_socket = self.context.socket(zmq.REQ)
task_socket.connect(self.upstream_task_endpoint)
try:
log.debug('sending request for task')
task_socket.send_pyobj(('task', self.id_str, None))
task = task_socket.recv_pyobj()
task_socket.close()
finally:
del task_socket
if task is None:
log.debug('no further task available')
task_avail = False
else:
log.debug('task received: {!r}'.format(task))
(task_id, fn, args, kwargs) = task
try:
def connect(self, server = None, port = None):
if self.connected:
self.disconnect()
self.context = zmq.Context()
self.server = (server if server else self.server)
self.port = (port if port else self.port)
# Socket to talk to server
self.transport = "tcp://{0}:{1}".format(self.server, self.port)
self.socket = self.context.socket(zmq.REQ)
self.socket.setsockopt(zmq.SNDTIMEO, self.get_timeout_msec())
self.socket.setsockopt(zmq.RCVTIMEO, self.get_timeout_msec())
self.socket.setsockopt(zmq.HEARTBEAT_IVL, 5000)
self.socket.setsockopt(zmq.HEARTBEAT_TIMEOUT, 60000)
self.socket.setsockopt(zmq.RECONNECT_IVL, 20)
self.socket.setsockopt(zmq.RECONNECT_IVL_MAX, 500)
try:
self.socket.connect(self.transport)
except zmq.error.ZMQError as e:
return RC_ERR("ZMQ Error: Bad server or port name: " + str(e))
self.connected = True
return RC_OK()
context = zmq.Context()
config = maglica.config.load()
pub_port = "5555"
if config.client.has_key("pub_port"):
pub_port = str(config.client["pub_port"])
rep_port = "5556"
if config.client.has_key("rep_port"):
rep_port = str(config.client["rep_port"])
subscriber = context.socket(zmq.SUB)
subscriber.connect(str("tcp://" + config.client["host"] + ":" + pub_port))
subscriber.setsockopt(zmq.SUBSCRIBE, 'copy')
requestor = context.socket(zmq.REQ)
requestor.connect(str("tcp://" + config.client["host"] + ":" + rep_port))
logging.info("copy worker started.")
virt = maglica.virt.Virt()
while True:
[address, args] = subscriber.recv_multipart()
args = json.loads(args)
name = args["name"]
dest = args["dest"]
conn = libvirt.open(virt.uri(dest))
domain_found = 1
try:
def stop(self):
"""Terminate all threads that were started by this class."""
# TODO - do we want to send a 'turn off' event to the display here?
# Terminate ZMQ-related threads
zmq_termination_request_socket = self.zmq_context.socket(zmq.REQ)
zmq_termination_request_socket.setsockopt(
zmq.LINGER, ZMQ_SOCKET_LINGER_MSEC
)
zmq_termination_request_socket.connect(
ZMQ_ADDRESS_INPROC.format(
identifier=self.zmq_scheduler_term_identifier
)
)
zmq_termination_request_socket.send_unicode('TERMINATE')
zmq_termination_request_socket.close()
self._zmq_scheduler_reply_thread.join()
self.zmq_context.term()
def start(self):
# Setup socket
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REQ)
if self.platform == "win32":
rndport = random.randrange(49152, 65536)
self.socket_addr = self.socket_addr + ":%s"%rndport
# Start the MATLAB server in a new process
print("Starting %s on ZMQ socket %s" % (self._program_name(), self.socket_addr))
print("Send 'exit' command to kill the server")
self._run_server()
# Start the client
self.socket.connect(self.socket_addr)
self.started = True
# Test if connection is established
if self.is_connected():