TCPServer端,tcp_server.py:
# -*- coding: utf-8 -*- #!/usr/bin/env python # @Time : 2018/5/15 17:34 # @Desc : # @File : tcp_server.py # @Software: PyCharm from tornado import ioloop, gen, iostream from tornado.tcpserver import TCPServer class MyTcpServer( TCPServer ): @gen.coroutine def handle_stream( self, stream, address ): try: while True: msg = yield stream.read_bytes( 20, partial = True ) print msg, 'from', address stream.write(str(msg)) yield stream.write( msg[::-1] ) if msg == 'over': stream.close() except iostream.StreamClosedError: pass if __name__ == '__main__': server = MyTcpServer() server.listen( 8036 ) server.start() ioloop.IOLoop.current().start()
tcp_client端,( 键盘输入)tcp_client.py:
# -*- coding: utf-8 -*- #!/usr/bin/env python # @Time : 2018/5/15 17:38 # @Desc : # @File : tcp_client.py # @Software: PyCharm from tornado import ioloop, gen, iostream from tornado.tcpclient import TCPClient @gen.coroutine def Trans(): stream = yield TCPClient().connect( 'localhost', 8036 ) try: while True: DATA = raw_input("Enter your input: "); yield stream.write( str(DATA) ) back = yield stream.read_bytes( 20, partial = True ) msg = yield stream.read_bytes(20, partial=True) print msg print back if DATA=='over': break except iostream.StreamClosedError: pass if __name__ == '__main__': ioloop.IOLoop.current().run_sync( Trans )
先启动tcp_server.py端,后启动tcp_client.py端,输入值结果如下:
tcp_server.py端:
tcp_client.py端:
温馨提示:使用该小程序前,得下载安装tornado==4.5.1,命令pip install tornado==4.5.1 ,用该命令前你得安装好pip。