Skip to content

Instantly share code, notes, and snippets.

@Greyvend
Last active July 26, 2017 16:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Greyvend/141327af9494058d4c75b712f326ff66 to your computer and use it in GitHub Desktop.
Save Greyvend/141327af9494058d4c75b712f326ff66 to your computer and use it in GitHub Desktop.
Tornado echo TCP Server & Client. Refer to the corresponding repo for the full working example: https://github.com/Databrawl/real_time_tcp/tree/3147a3f4bddf70616f19a7e4c41df6118d5f348a.
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.tcpclient import TCPClient
class Client(TCPClient):
msg_separator = b'\r\n'
@gen.coroutine
def run(self, host, port):
stream = yield self.connect(host, port)
while True:
data = input(">> ").encode('utf8')
data += self.msg_separator
if not data:
break
else:
yield stream.write(data)
data = yield stream.read_until(self.msg_separator)
body = data.rstrip(self.msg_separator)
print(body)
if __name__ == '__main__':
Client().run('localhost', 5567)
print('Connecting to server socket...')
IOLoop.instance().start()
print('Socket has been closed.')
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.iostream import StreamClosedError
from tornado.tcpserver import TCPServer
class Server(TCPServer):
message_separator = b'\r\n'
@gen.coroutine
def handle_stream(self, stream, address):
while True:
try:
request = yield stream.read_until(self.message_separator)
except StreamClosedError:
stream.close(exc_info=True)
return
try:
yield stream.write(request)
except StreamClosedError:
stream.close(exc_info=True)
return
if __name__ == '__main__':
Server().listen(5567)
print('Starting the server...')
IOLoop.instance().start()
print('Server has shut down.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment