Skip to content

Instantly share code, notes, and snippets.

@biggers biggers/tcpclient.py
Last active Jan 2, 2018

Embed
What would you like to do?
"continously-running" Tornado TCP client example -- sends to 'tornado/demos/tcpecho/server.py'
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="127.0.0.1", 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/server.py'
Derived from: tornado/demos/tcpecho/client.py
"""
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
@gen.coroutine
def run(self, loop, service=None):
logger.info("in EchoClient.run() ...")
if service is None:
service = yield TCPClient().connect(options.host, options.port)
try:
our_msg_bytes = self.get_random_word() +'\n'
yield service.write(our_msg_bytes.encode())
logger.info("Sent to server: {}".format(our_msg_bytes.strip()))
data = yield service.read_until(b"\n")
logger.info("Response: %s", data.decode().strip())
except StreamClosedError:
logger.warning("Lost our server at host %s", options.host)
loop.stop()
except Exception as e:
print(e)
# reschedule.me!
loop.call_later(options.delay, self.run, loop, service)
if __name__ == "__main__":
options.parse_command_line()
# import pdb; pdb.set_trace()
# pp options.as_dict()
client = EchoClient()
logger.info("Sending data on TCP port %d", options.port)
loop = IOLoop.current()
loop.call_later(options.delay, client.run, loop)
loop.start()
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.