import tornado.ioloop import tornado.iostream class EchoServer: def __init__(self, socket): self.stream = tornado.iostream.IOStream(socket) self.stream.read_until_close(callback=self.handle) def handle(self, data): self.stream.write(data) server_socket = tornado.netutil.bind_sockets(8888)[0] tornado.ioloop.IOLoop.current().add_handler(server_socket.fileno(), EchoServer, tornado.ioloop.IOLoop.READ) tornado.ioloop.IOLoop.current().start()
import tornado.ioloop import tornado.iostream import tornado.httpclient class HttpClient: def __init__(self, url): self.stream = None self.request = tornado.httpclient.HTTPRequest(url) self.client = tornado.httpclient.AsyncHTTPClient() def connect(self): self.stream = tornado.iostream.IOStream(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) self.stream.connect(('google.com', 80), self.send_request) def send_request(self): self.stream.write(self.request) def handle_response(self, response): print(response.body) client = HttpClient('http://google.com') client.connect() tornado.ioloop.IOLoop.current().start()This code creates a simple HTTP client that connects to google.com and fetches the page contents asynchronously. The IOStream class is used to create a TCP socket and to send and receive data over the socket. The HTTP request is represented as a tornado.httpclient.HTTPRequest object and sent over the socket using the IOStream.write method. The response is handled asynchronously in the `handle_response` method, which simply prints the response body to the console. Overall, the Tornado.iostream package library is an essential part of the Python Tornado framework, which is useful for building high-performance networking applications.