-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrespond.py
More file actions
executable file
·77 lines (58 loc) · 2.16 KB
/
respond.py
File metadata and controls
executable file
·77 lines (58 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import stdout
import random
import string
import txnats
from twisted.logger import globalLogPublisher
from simple_log_observer import simpleObserver
from twisted.logger import Logger
log = Logger()
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.endpoints import connectProtocol
responder_id = ''.join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
def respond_on_msg(nats_protocol, sid, subject, reply_to, payload):
"""
Write the message information to standard out, and if
there is a reply_to, publish a message to it.
"""
stdout.write("sid: {}, subject: {}, reply-to: {}\r\n".format(
sid, subject, reply_to))
stdout.write(payload.decode())
stdout.write("\r\n*")
if reply_to:
nats_protocol.pub(
reply_to, "Roger, from {}!".format(responder_id).encode())
def listen(nats_protocol):
"""
When the protocol is first connected, make a subscription.
"""
log.info("HELLO LISTEN")
nats_protocol.sub("ssshh", '6', on_msg=respond_on_msg)
def create_client(reactor, host, port):
"""
Start a Nats Protocol and connect it to a NATS endpoint over TCP4
which subscribes a subject with a callback that sends a response
if it gets a reply_to.
"""
log.info("Start client.")
point = TCP4ClientEndpoint(reactor, host, port)
nats_protocol = txnats.io.NatsProtocol(verbose=False, on_connect=listen)
# Because NatsProtocol implements the Protocol interface, Twisted's
# connectProtocol knows how to connected to the endpoint.
connecting = connectProtocol(point, nats_protocol)
# Log if there is an error making the connection.
connecting.addErrback(lambda np: log.info("{p}", p=np))
# Log what is returned by the connectProtocol.
connecting.addCallback(lambda np: log.info("{p}", p=np))
return connecting
def main(reactor):
host = "demo.nats.io"
port = 4222
create_client(reactor, host, port)
if __name__ == '__main__':
globalLogPublisher.addObserver(simpleObserver)
main(reactor)
reactor.run()