• tornado tcp 框架 demo


    server

    #!/usr/bin/env python
    
    import logging
    from tornado.ioloop import IOLoop
    from tornado import gen
    from tornado.iostream import StreamClosedError
    from tornado.tcpserver import TCPServer
    from tornado.options import options, define
    
    define("port", default=9888, help="TCP port to listen on")
    logger = logging.getLogger(__name__)
    
    
    class EchoServer(TCPServer):
        @gen.coroutine
        def handle_stream(self, stream, address):
            while True:
                try:
                    data = yield stream.read_until(b"
    ")
                    logger.info("Received bytes: %s", data)
                    if not data.endswith(b"
    "):
                        data = data + b"
    "
                        logger.info(data)
                    yield stream.write(data)
                except StreamClosedError:
                    logger.warning("Lost client at host %s", address[0])
                    break
                except Exception as e:
                    print(e)
    
    
    if __name__ == "__main__":
        options.parse_command_line()
        server = EchoServer()
        server.listen(options.port)
        logger.info("Listening on TCP port %d", options.port)
        IOLoop.current().start()

    client

    # -*- coding: utf-8 -*-
    
    import socket
    import json
    import time
    
    def assemble(data):
        return json.dumps(data)
    host="127.0.0.1"
    port=9888
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((host,port))
    data={"req":"get","obj":"ver","seq":1,"param":{}}
    message=assemble(data)
    s.send(message.encode("utf-8")+b"
    ")
    while(1):
        x=s.recv(1024)
        if(x):
            print("server to client result:",x)
    s.close()

  • 相关阅读:
    故障分析 | 全局读锁一直没有释放,发生了什么?
    日常笔记
    BCC观测工具的使用
    wireshark的应用
    SQL基础之实现累加值
    SQL查询语句使用rand()的执行效率与优化
    MySQL主从复制相关问题
    LVM不停机扩容
    gtid跳过错误的方法
    IO诊断文档
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10524036.html
Copyright © 2020-2023  润新知