没有用于此的本机 API,但您拥有所需的所有部分。helloworld
这是来自 repo的示例的修改版本。
class PeerSet(object):
def __init__(self):
self._peers_lock = threading.RLock()
self._peers = {}
def connect(self, peer):
print("Peer {} connecting".format(peer))
with self._peers_lock:
if peer not in self._peers:
self._peers[peer] = 1
else:
self._peers[peer] += 1
def disconnect(self, peer):
print("Peer {} disconnecting".format(peer))
with self._peers_lock:
if peer not in self._peers:
raise RuntimeError("Tried to disconnect peer '{}' but it was never connected.".format(peer))
self._peers[peer] -= 1
if self._peers[peer] == 0:
del self._peers[peer]
def peers(self):
with self._peers_lock:
return self._peers.keys()
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def __init__(self):
self._peer_set = PeerSet()
def _record_peer(self, context):
def _unregister_peer():
self._peer_set.disconnect(context.peer())
context.add_callback(_unregister_peer)
self._peer_set.connect(context.peer())
def SayHello(self, request, context):
self._record_peer(context)
for i in range(10):
print("[thread {}] Peers: {}".format(threading.currentThread().ident, self._peer_set.peers()))
time.sleep(1)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
这将为您提供如下输出:
[thread 139905506195200] Peers: [u'ipv6:[::1]:57940', u'ipv6:[::1]:57930', u'ipv6:[::1]:57926', u'ipv6:[::1]:57920', u'ipv6:[::1]:57934']
正如 Ding 上面评论的那样,channelz可能也很适合你。