<blockquote>
<p><strong>Q</strong> : <em>say the server is not up in that case the <code>recv()</code> in the client will be blocked forever which I don't want.</em></p>
</blockquote>
<p>ZeroMQ是在分布式系统中进行智能信令/消息传递的极好框架</p>
<p>让我们描绘一个<strong>主要是非阻塞的</strong>操作方法的演示,并给出一些关于在进程终止之前如何获得资源以及如何优雅地释放资源的一些启示。在</p>
<p>也许阅读一下<strong>部分的主要概念差异也会有所帮助。在</p>
<p>希望您能喜欢这个和更深入的实验<a href="https://stackoverflow.com/search?tab=votes&q=user%3A3666197%20%5Bzeromq%5D">StackOverflow <strong>resources</strong></a>如何最好地利用ZeroMQ Zen of Zero的所有能力:</p>
<p><strong><code>Server.py</code></strong></p>
<pre><code> aContext = zmq.Context()
aLightHouse = aContext.socket( zmq.PUB )
aRepSocket = aContext.socket( zmq.REP )
aRepSocket.setsockopt( zmq.LINGER, 0 )
aRepSocket.setsockopt( zmq.COMPLETE, 1 )
aRepSocket.bind( "tcp://*:2222" )
aLightHouse.bind( "tcp://*:3333" )
aLightHouse.setsockopt( zmq.LINGER, 0 )
aLightHouse.setsockopt( zmq.CONFLATE, 1 )
aLightHouse_counter = 0
#
print( "INF: Server InS: ZeroMQ({0:}) going RTO:".format( zmq.zmq_version() ) )
#
while True:
try:
aLightHouse_counter += 1
aLightHouse.send( "INF: server-RTO blink {0:}".format( repr( aLightHouse_counter ) ),
zmq.NOBLOCK
)
if ( 0 < aRepSocket.poll( 0, zmq.POLLIN ) ):
try:
message = aRepSocket.recv( zmq.NOBLOCK ); print( "INF: .recv()ed {0:}".format( message ) )
pass; aRepSocket.send( b"Ack", zmq.NOBLOCK ); print( "INF: .sent() ACK" )
except:
# handle EXC: based on ...
print( "EXC: reported as Errno == {0:}".format( zmq.zmq_errno() ) )
else:
# NOP / Sleep / do other system work-units to get processed during the infinite-loop
except:
# handle EXC:
print( "EXC: will break ... and terminate OoS ..." )
break
#
print( "INF: will soft-SIG Server going-OoS..." )
aLightHouse.send( "INF: server goes OoS ... " )
#
print( "INF: will .close() and .term() resources on clean & graceful exit..." )
Sleep( 0.987654321 )
aRepSocket.unbind( "tcp://*:2222" )
aRepSocket.close()
aLightHouse.unbind( "tcp://*:3333" )
aLightHouse.close()
aContext.term()
#
print( "INF: over and out" )
</code></pre>
<p><strong><code>Client.py</code></strong></p>
^{pr2}$