from tornado import ioloop, iostream, netutil def on_connect(sock): stream = iostream.IOStream(sock) stream.read_until_close(on_close, on_data) def on_data(data): print("Received:", data) def on_close(): print("Connection closed.") server = netutil.TCPServer() server.bind(8888) server.start(0) ioloop.IOLoop.current().add_callback(server.start_accepting) ioloop.IOLoop.current().start()
from tornado import ioloop, iostream stream = iostream.IOStream(socket) def write_callback(): print("Data sent successfully.") data = b"Hello, world!" stream.write(data, write_callback) ioloop.IOLoop.current().start()In this example, we create an IOStream object around an existing socket, and use its write() method to send data to the remote endpoint. We also register a callback function that is called when the data has been successfully sent. The IOLoop starts and runs indefinitely to handle events. In conclusion, Tornado's IOStream is a powerful and versatile library for handling I/O operations in Python. It provides an asynchronous interface that is efficient and scalable, making it suitable for building high-performance web applications.