本文整理汇总了Python中nanomsg.Socket.set_string_option方法的典型用法代码示例。如果您正苦于以下问题:Python Socket.set_string_option方法的具体用法?Python Socket.set_string_option怎么用?Python Socket.set_string_option使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nanomsg.Socket
的用法示例。
在下文中一共展示了Socket.set_string_option方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('-n', '--rate-limit', metavar="NUM",
help="Number of requests to issue per second (default %(default)d)",
default=100, type=float)
ap.add_argument('-m', '--max-value', metavar="NUM",
help="Maximum number that's sent for factorizing (default %(default)d)",
default=10**12, type=int)
ap.add_argument('--min-value', metavar="NUM",
help="Maximum number that's sent for factorizing (default %(default)d)",
default=10**11, type=int)
ap.add_argument('--topology', metavar="URL", required=True,
help="Url for topology to join to")
options = ap.parse_args()
delay = 1.0 / options.rate_limit
sock = Socket(PUSH)
sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")
sock.configure(options.topology)
while True:
tm = time.time()
num = random.randint(options.min_value, options.max_value)
sock.send(str(num))
to_sleep = tm + delay - time.time()
if to_sleep > 0:
time.sleep(to_sleep)
示例2: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('-n', '--requests', metavar="NUM",
help="Number of requests to issue (default %(default)d)",
default=10000, type=int)
ap.add_argument('-c', '--concurrent', metavar="NUM",
help="Number of requests sent simultaneously (default %(default)d)",
default=1000, type=int)
ap.add_argument('-m', '--max-value', metavar="NUM",
help="Maximum number that's sent for factorizing (default %(default)d)",
default=10**12, type=int)
ap.add_argument('--min-value', metavar="NUM",
help="Maximum number that's sent for factorizing (default %(default)d)",
default=10**11, type=int)
ap.add_argument('--topology', metavar="URL", required=True,
help="Url for topology to join to")
options = ap.parse_args()
sock = Socket(REQ, domain=AF_SP_RAW)
sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "client")
sock.configure(options.topology)
start_time = time.time()
reqiter = requests(options)
req = {}
for i in range(options.concurrent):
rid, val = next(reqiter)
sock.send(b'\x00\x00\x00\x00' + struct.pack('>L', rid | 0x80000000)
+ str(val).encode('ascii'))
req[rid] = val
errors = 0
sp = 0
n = 0
while req:
data = sock.recv()
rid = struct.unpack_from('>L', data)[0] & ~0x80000000
factors = map(int, data[4:].decode('ascii').split(','))
checkval = reduce(int.__mul__, factors)
if rid not in req:
sp += 1
elif req.pop(rid) != checkval:
errors += 1
else:
n += 1
try:
rid, val = next(reqiter)
except StopIteration:
continue
else:
sock.send(b'\x00\x00\x00\x00' + struct.pack('>L', rid | 0x80000000)
+ str(val).encode('ascii'))
req[rid] = val
sec = time.time() - start_time
print("Done", options.requests, "requests in", sec,
"seconds, errors:", errors, ", spurious messages:", sp)
示例3: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--topology', metavar="URL", required=True,
help="Url for topology to join to")
options = ap.parse_args()
sock = Socket(PULL)
sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")
sock.configure(options.topology)
while True:
data = sock.recv()
num, factors = data.decode('ascii').split('=', 1)
factors = map(int, factors.split('*'))
checkval = reduce(int.__mul__, factors)
assert int(num) == checkval
示例4: NanomsgSubscriber
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
class NanomsgSubscriber(HiddenSubscriber):
""" Subscriber class subscribing to a certain topic
Attributes:
context (zmq.Context):
socket (Socket): Socket object of ZMQ context
topic (String): Topic subscriber subscribes to
"""
def __init__(self, url, topic):
""" Initializes object
Args:
url (String): url to publish messages to
topic (String): Topic to publish messages under
"""
super(NanomsgSubscriber, self).__init__(topic)
self._socket = Socket(SUB)
self._socket.recv_timeout = 500 # Wait 500ms for receiving msgs
self._socket.connect(url)
self._socket.set_string_option(SUB, SUB_SUBSCRIBE, topic + '|')
self._logger = logging.getLogger('NanomsgSubscriber')
def receive(self):
""" Receives a message
Returns:
String
"""
message = self._socket.recv()
return message[len(self.topic) + 1:]
def __enter__(self):
""" Statement used for the `` with ... as ...:`` returns
the object to use in the ``with`` block
Returns:
NanomsgSubscriber
"""
return self
def __exit__(self, exc_type, exc_value, traceback):
""" Executed when leaving ``with`` block, regardless whether
because of an exception or normal program flow
"""
self._socket.close()
示例5: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
def main():
ap = argparse.ArgumentParser()
gr = ap.add_mutually_exclusive_group()
gr.add_argument('--rep', metavar="URL",
help="The topology url of replier socket")
gr.add_argument('--pullpush', metavar="URL", nargs=2,
help="The topology urls of pull and push sockets for request processing")
options = ap.parse_args()
if options.rep:
sock = Socket(REP)
sock.configure(options.rep)
sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "rep")
read = write = sock
else:
read = Socket(PULL)
read.set_string_option(SOL_SOCKET, SOCKET_NAME, "pull")
write = Socket(PUSH)
write.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")
read.configure(options.pullpush[0])
write.configure(options.pullpush[1])
while True:
num = int(read.recv())
res = factorize_naive(num)
formula = str(num) + '=' + '*'.join(map(str, res))
write.send(formula.encode('ascii'))
示例6: LogSub
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
class LogSub(QThread):
def __init__(self, url):
self.socket = Socket(SUB)
self.url = url
self.handlers = []
super().__init__()
def register_handler(self, handler):
self.handlers.append(handler)
def run(self):
self.socket.set_string_option(SUB, SUB_SUBSCRIBE, b'')
self.socket.connect(self.url)
while True:
try:
msg = self.socket.recv()
msg_pack = msgpack.unpackb(msg, encoding='utf-8')
for h in self.handlers:
h(**msg_pack)
except nanomsg.NanoMsgAPIError as e:
raise
示例7: ClientMq
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
class ClientMq(object):
def __init__(self, ui_event_engine, outgoing_quue):
self._ui_event_engine = ui_event_engine
self._outgoing_quue = outgoing_quue
self._tick_sock = Socket(SUB)
self._msg_sock = Socket(PAIR)
self._active = False
self._thread = Thread(target=self._run)
def _run(self):
while self._active:
try:
msg1 = self._tick_sock.recv(flags=1)
msg1 = msg1.decode("utf-8")
if msg1 is not None and msg1.index('|') > 0:
if msg1[-1] == '\0':
msg1 = msg1[:-1]
k = TickEvent()
k.deserialize(msg1)
self._ui_event_engine.put(k)
except Exception as e:
pass
try:
msg2 = self._msg_sock.recv(flags=1)
msg2 = msg2.decode("utf-8")
if msg2 is not None and msg2.index('|') > 0:
if msg2[-1] == '\0':
msg2 = msg2[:-1]
if msg2[-1] == '\x00':
msg2 = msg2[:-1]
v = msg2.split('|')
if v[0] == 's':
m = OrderStatusEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'f':
m = FillEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'n':
m = PositionEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'h':
m = HistoricalEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'u':
m = AccountEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'r':
m = ContractEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
elif v[0] == 'm':
m = GeneralEvent()
m.deserialize(msg2)
self._ui_event_engine.put(m)
pass
except Exception as e:
pass
# print('PAIR error: '+ str(i) + '' + str(e));
# time.sleep(1)
try:
msg3 = self._outgoing_quue.get(False)
self._msg_sock.send(msg3, flags=1)
except Exception as e:
pass
def start(self, timer=True):
"""
start the mq thread
"""
self._tick_sock.connect('tcp://127.0.0.1:55555')
self._tick_sock.set_string_option(SUB, SUB_SUBSCRIBE, '') # receive msg start with all
self._msg_sock.connect('tcp://127.0.0.1:55558')
self._active = True
if not self._thread.isAlive():
self._thread.start()
def stop(self):
"""
stop the mq thread
"""
self._active = False
if self._thread.isAlive():
self._thread.join()
示例8: __init__
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
class NodeEditor:
def __init__(self, mouse, gltext, conf):
self.conf = conf
self.mouse = mouse # TODO: use a special mouse object instead of the editor_main object directly.
self.gltext = gltext
self.nodes = []
self.links = []
self.nodes_dict = {} # integers. 16-bit node addresses
self.links_dict = {} # a pair of node objects. (node1, node2) is equivalent to (node2, node1), but only one pair exists in links_dict
self.mouse_hover = False
self.mouse_dragging = False
self.selected = None
self.selected_pos_ofs = vector.Vector()
h = 0. # 10 cm from the ground. nnope. for now, h has to be 0.
r = 1.
for i in range(10):
a = float(i) / (r + 10) * 15.
x, y = r * math.sin(a), r * math.cos(a)
r += 0.5
n = Node( vector.Vector((x, h, y)), i + 1, self._get_node_color(i+1), gltext )
self.append_node(n)
# n = Node( vector.Vector((0., h, 0.)), 1, gltext ); self.append_node(n)
# n = Node( vector.Vector((1., h, 0.)), 2, gltext ); self.append_node(n)
# n = Node( vector.Vector((2., h, -1.)), 3, gltext ); self.append_node(n)
# n = Node( vector.Vector((-2., h, 2.)), 4, gltext ); self.append_node(n)
# n = Node( vector.Vector((-1., h, 2.)), 5, gltext ); self.append_node(n)
# n = Node( vector.Vector((-2., h, 1.)), 6, gltext ); self.append_node(n)
# n = Node( vector.Vector((-1., h, 0.)), 7, gltext ); self.append_node(n)
# n = Node( vector.Vector((-1.5, h, -1.)), 8, gltext ); self.append_node(n)
# n = Node( vector.Vector((0.5, h, 1.)), 9, gltext ); self.append_node(n)
# n = Node( vector.Vector((-1.4, h, 0.5)), 10, gltext ); self.append_node(n)
#n.attrs["etx"] = 44
self.s1 = Socket(SUB)
self.s1.connect('tcp://127.0.0.1:55555')
self.s1.set_string_option(SUB, SUB_SUBSCRIBE, '')
def _get_link(self, src_node, dst_node):
""" create a new link object if not found from self.links.
fill self.links and self.links_dict (the dict both with src_node_id and dst_node_id) """
if (src_node, dst_node) in self.links_dict:
return self.links_dict[(src_node, dst_node)]
elif (dst_node, src_node) in self.links_dict:
return self.links_dict[(dst_node, src_node)]
else:
link = Link(src_node, dst_node)
self.links.append(link)
self.links_dict[(src_node, dst_node)] = link
return link
def _get_node_color(self, origin_node_id):
if origin_node_id == 10:
return 0.753, 0.753, 0.753, 1.
if origin_node_id == 9:
return 0.824, 0.412, 0.118, 1.
if origin_node_id == 8:
return 1.000, 0.000, 1.000, 1.
if origin_node_id == 7:
return 1.000, 1.000, 0.000, 1.
if origin_node_id == 6:
return 1.000, 0.627, 0.478, 1.
if origin_node_id == 5:
return 0.498, 1.000, 0.000, 1.
if origin_node_id == 4:
return 0.000, 1.000, 1.000, 1.
if origin_node_id == 3:
return 1.000, 0.922, 0.804, 1.
if origin_node_id == 2:
return 0.871, 0.722, 0.529, 1.
if origin_node_id == 1:
return 0.000, 0.749, 1.000, 1.
return 0.8, 0.8, 0.8, 1.0
def append_node(self, node):
assert node.node_id not in self.nodes_dict
self.nodes.append(node)
self.nodes_dict[node.node_id] = node
def tick(self, dt, keys):
for link in self.links:
link.tick(dt)
for node in self.nodes:
node.tick(dt)
try:
while 1:
d = self.s1.recv(flags=DONTWAIT)
d = d.strip()
if d:
if d.startswith("data etx"):
# ['data', 'etx', '0001000000000200', 'node', '0A', 'index', '0', 'neighbor', '8', 'etx', '10', 'retx', '74']
d = d.split()
#llog.info(d)
node_id = int(d[4], 16)
# filter out empty rows
#.........这里部分代码省略.........
示例9: get_delta_packets
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import set_string_option [as 别名]
class NodeEditor:
#STATE_PLAYBACK_ON_EDGE = 0x01 #
STATE_PLAYBACK = 0x02 # playback from random place
STATE_PAUSED = 0x03
# seek
# get_delta_packets(dt)
# get_current_timestamp
def __init__(self, nugui, mouse, gltext, conf):
self.conf = conf
self.mouse = mouse # TODO: use a special mouse object instead of the editor_main object directly.
self.gltext = gltext
self.nugui = nugui
self.world = world.World("ff", self.conf)
self.underworld = world.World("", self.conf) # not visible. used serializing keyframes
self.mouse_x = 0.
self.mouse_y = 0.
self.mouse_hover = False
self.mouse_dragging = False
self.selected = None
self.selected_pos_ofs = vector.Vector()
self.node_renderer = renderers.NodeRenderer(self.gltext)
self.link_renderer = renderers.LinkRenderer()
# saved when closing the windows. loaded at startup.
self.session_filename = os.path.normpath(os.path.join(self.conf.path_database, "session_conf.txt"))
self.load_session()
self.recording = True
self.state = self.STATE_PLAYBACK
self.worldstreamer = world_streamer.WorldStreamer(sync_window_seconds=self.conf.sync_depth_seconds)
#self.current_playback_time = 0. # timepoint of the simulation that is currently visible on screen. can be dragged around with a slider.
self.timeslider_end_time = 0.
self.graph_window = graph_window.GraphWindow(self.gltext)
self.graph_window_initialized = False
self.s1 = Socket(SUB)
self.s1.connect('tcp://127.0.0.1:55555')
self.s1.set_string_option(SUB, SUB_SUBSCRIBE, '')
def tick(self, dt, keys):
self.world.tick(dt)
self.underworld.tick(dt)
self.net_poll_packets()
fresh_packets = self.worldstreamer.tick()
for p in fresh_packets:
self.handle_packet(p[1], self.underworld, barebones=True)
if self.state == self.STATE_PLAYBACK:
packets = self.worldstreamer.get_delta_packets(dt)
for p in packets:
self.handle_packet(p[1], self.world)
if self.worldstreamer.need_keyframe():
llog.info("need keyframe!")
w = self.underworld.serialize_world()
#import pprint
#llog.info("\n\n\nSAVING")
#llog.info(pprint.pformat(w))
self.worldstreamer.put_keyframe(w)
# always set the graph start 10 seconds before the first sample time. user-friendly start condition for the zoom-scroller.
if self.worldstreamer.start_time != None and not self.graph_window_initialized:
self.graph_window_initialized = True
self.graph_window.set_totalsample_start(self.worldstreamer.start_time - 10.)
self.graph_window.set_totalsample_end(self.worldstreamer.end_time)
self.graph_window.set_sample_visibility(self.worldstreamer.start_time - 10., self.worldstreamer.end_time)
if self.graph_window_initialized:
self.graph_window.set_totalsample_end(self.worldstreamer.end_time)
self.graph_window.tick()
if self.graph_window_initialized:
# if the graph was moved by keyboard/mouse
if self.graph_window.wanted_x2_was_moved:
self.graph_window.wanted_x2_was_moved = False
newtime = self.graph_window.wanted_visiblesample_x2
if newtime != self.worldstreamer.current_time:
llog.info("seeking from %.2f to %.2f between %.2f %.2f", self.worldstreamer.current_time, newtime, self.worldstreamer.start_time, self.worldstreamer.end_time)
keyframe, packets = self.worldstreamer.seek(newtime)
self.world.deserialize_world(keyframe)
llog.info("seeking returned %i packets", len(packets))
if packets:
# calc the timestamp from where to start using animations. use only 2 seconds worth, because
# it's not very nice to animate all packets at once if seek returned 30 minutes worth of packets for example.
# TODO: but if the keyframe is too close to the seek time, then we won't get even 2 seconds worth of packets.
# then we'll have to use the previous keyframe. oh, too much work..
animations_start = packets[-1][0] - 2.
#.........这里部分代码省略.........