tornado官网文档:
服务端代码
#!/usr/bin/python#coding=utf-8from tornado.tcpserver import TCPServerfrom tornado.netutil import bind_socketsfrom tornado.ioloop import IOLoopfrom tornado import processfrom tornado.options import define, optionsdefine("port", default=10002, help="TCP port to use")define("server", default="127.0.0.1", help="Run as the echo server")define("localfile", default="/home/xxx/xxx/testtcp/result.txt", help="local file")define("encoding", default="utf-8", help="String encoding")"""业务逻辑类,用于处理逻辑"""class Connection(object): def __init__(self, stream, address): self._stream = stream self._address = address #向client端发送“101”字符,用于表示建立tcp服务成功 self.send_message("101") self.read_message() #读取数据 def read_message(self): #从流中读取client端发送过来的数据,且规定每条数据以“\n”标示结束、每条数据不得超过2048个字节 self._stream.read_until("\n", self.broadcast_messages, 2048) #广播数据、处理逻辑 def broadcast_messages(self, data): #如果数据不为空,则写本地文件,并向client端发送“102”字符,用于表示接收数据成功 if data: self.writefile(data) self.send_message("102") self.close_stream() #向client端发送数据 def send_message(self, data): self._stream.write(data) #关闭流 def close_stream(self): self._stream.close() #捉追加写本地文件 def writefile(self, data): with open(options.localfile, 'a') as local_file: local_file.write(data)"""数据服务类,继承自TCPServer"""class DataServer(TCPServer): def handle_stream(self, stream, address): #当连接到来时, 这个函数被调用, 传入stream(IOStream对象, 而不是原始的fd)和address, 之后就可以用IOStream对象方法收发消息了 Connection(stream, address)if __name__ == '__main__': print "Server start ......" #多进程模式 sockets = bind_sockets(options.port, options.server) process.fork_processes(0) server = DataServer() server.add_sockets(sockets) IOLoop.current().start() # 单进程模式 # server = DataServer() # server.listen(options.port, options.server) # IOLoop.current().start()