栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

零mq:socket.recv()调用被阻止

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

零mq:socket.recv()调用被阻止

如果传递

zmq.NOBLOCK
flag参数,zmq.Socket.recv将不会阻塞。

文档说:

If NOBLOCK is set, this method will raise a ZMQError with EAGAIN if a message is not ready.

zmq会将接收到的消息放入队列中,并且每次recv()调用都会返回一条消息,直到此队列耗尽为止,之后引发ZMQError。

下面示例中使用的zmq.Again是一个

wrapperfor zmq.EAGAIN

例如:

while True:    try:        #check for a message, this will not block        message = socket.recv(flags=zmq.NOBLOCK)        #a message has been received        print "Message received:", message    except zmq.Again as e:        print "No message received yet"    # perform other important stuff    time.sleep(10)

sub_client.py
示例可能被编写为使用如下非阻塞行为:

import sys, timeimport zmqport = "5556"if len(sys.argv) > 1:    port =  sys.argv[1]    int(port)# Socket to talk to servercontext = zmq.Context()socket = context.socket(zmq.SUB)print "Collecting updates from weather server..."socket.connect ("tcp://localhost:%s" % port)# Subscribe to zippre, default is NYC, 10001topicfilter = "10001"socket.setsockopt(zmq.SUBSCRIBE, topicfilter)# Process 5 updatestotal_value = 0received_value_count = 0do_receive_loop = Truewhile do_receive_loop:    try:        #process all messages waiting on subscribe socket        while True: #check for a message, this will not block string = socket.recv(flags=zmq.NOBLOCK) #message received, process it topic, messagedata = string.split() total_value += int(messagedata) print ('{} {}'.format(topic, messagedata)) #check if we have all the messages we want received_value_count += 1 if received_value_count > 4:     do_receive_loop = False     break    except zmq.Again as e:        #No messages waiting to be processed        pass    #Here we can do other stuff while waiting for messages    #contemplate answer to 'The Last Question'    time.sleep(15)    print "INSUFFICIENT DATA FOR MEANINGFUL ANSWER"print('Avg data value for topic {} was {}'.format(topicfilter, (total_value/5)))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号