Skip to content

Instantly share code, notes, and snippets.

@biggers biggers/
Last active Jan 2, 2018

What would you like to do?
"continously-running" Tornado TCP client example -- sends to 'tornado/demos/tcpecho/'
import time
import logging
from tornado.options import options, define
from tornado import gen
from tornado.tcpclient import TCPClient
from tornado.iostream import StreamClosedError
from tornado.ioloop import IOLoop
define("host", default="", help="TCP server host")
define("port", default=9888, help="TCP port to connect to")
define("sleep_for", default=2.0, help="Sleep time before next message-send")
define("delay", default=1.5, help="delay for re(run) callback")
logger = logging.getLogger(__name__)
class EchoClient(TCPClient):
"continously-running" TCP client - sends to 'tornado/demos/tcpecho/'
Derived from: tornado/demos/tcpecho/
def get_random_word(self, length=10):
""" kudos to StackOverflow...
import random
random_word = ""
for i in range(length):
random_word += (str(chr(random.randint(97,122))))
return random_word
def run(self, loop, service=None):"in ...")
if service is None:
service = yield TCPClient().connect(, options.port)
our_msg_bytes = self.get_random_word() +'\n'
yield service.write(our_msg_bytes.encode())"Sent to server: {}".format(our_msg_bytes.strip()))
data = yield service.read_until(b"\n")"Response: %s", data.decode().strip())
except StreamClosedError:
logger.warning("Lost our server at host %s",
except Exception as e:
loop.call_later(options.delay,, loop, service)
if __name__ == "__main__":
# import pdb; pdb.set_trace()
# pp options.as_dict()
client = EchoClient()"Sending data on TCP port %d", options.port)
loop = IOLoop.current()
loop.call_later(options.delay,, loop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.