A non-blocking, single-threaded TCP server.
TCPServer(ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, read_chunk_size: int = None)¶
A non-blocking, single-threaded TCP server.
from tornado.tcpserver import TCPServer from tornado.iostream import StreamClosedError from tornado import gen class EchoServer(TCPServer): async def handle_stream(self, stream, address): while True: try: data = await stream.read_until(b"\n") await stream.write(data) except StreamClosedError: break
To make this server serve SSL traffic, send the
ssl_optionskeyword argument with an
ssl.SSLContextobject. For compatibility with older versions of Python
ssl_optionsmay also be a dictionary of keyword arguments for the
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"), os.path.join(data_dir, "mydomain.key")) TCPServer(ssl_options=ssl_ctx)
TCPServerinitialization follows one of three patterns:
listen: simple single-process:
server = TCPServer() server.listen(8888) IOLoop.current().start()
server = TCPServer() server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.current().start()
add_sockets: advanced multi-process:
sockets = bind_sockets(8888) tornado.process.fork_processes(0) server = TCPServer() server.add_sockets(sockets) IOLoop.current().start()
add_socketsinterface is more complicated, but it can be used with
tornado.process.fork_processesto give you more flexibility in when the fork happens.
add_socketscan also be used in single-process servers if you want to create your listening sockets in some way other than
New in version 3.1: The
Changed in version 5.0: The
io_loopargument has been removed.
listen(port: int, address: str = '') → None¶
Starts accepting connections on the given port.
This method may be called more than once to listen on multiple ports.
listentakes effect immediately; it is not necessary to call
TCPServer.startafterwards. It is, however, necessary to start the
add_sockets(sockets: Iterable[socket.socket]) → None¶
Makes this server start accepting connections on the given sockets.
socketsparameter is a list of socket objects such as those returned by
add_socketsis typically used in combination with that method and
tornado.process.fork_processesto provide greater control over the initialization of a multi-process server.
add_socket(socket: socket.socket) → None¶
Singular version of
add_sockets. Takes a single socket object.
bind(port: int, address: str = None, family: socket.AddressFamily = <AddressFamily.AF_UNSPEC: 0>, backlog: int = 128, reuse_port: bool = False) → None¶
Binds this server to the given port on the given address.
Address may be either an IP address or hostname. If it’s a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either
socket.AF_INET6to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available.
This method may be called multiple times prior to
startto listen on multiple ports or interfaces.
Changed in version 4.4: Added the
start(num_processes: Optional[int] = 1, max_restarts: int = None) → None¶
Starts this server in the
By default, we run the server in this process and do not fork any additional child process.
If num_processes is
Noneor <= 0, we detect the number of cores available on this machine and fork that number of child processes. If num_processes is given and > 1, we fork that specific number of sub-processes.
Since we use processes and not threads, there is no shared memory between any server code.
Note that multiple processes are not compatible with the autoreload module (or the
tornado.web.Applicationwhich defaults to True when
debug=True). When using multiple processes, no IOLoops can be created or referenced until after the call to
num_processesother than 1 are not supported on Windows.
max_restartsargument is passed to
Changed in version 6.0: Added
stop() → None¶
Stops listening for new connections.
Requests currently in progress may still continue after the server is stopped.
handle_stream(stream: tornado.iostream.IOStream, address: tuple) → Optional[Awaitable[None]]¶
Override to handle a new
IOStreamfrom an incoming connection.
This method may be a coroutine; if so any exceptions it raises asynchronously will be logged. Accepting of incoming connections will not be blocked by this coroutine.
TCPServeris configured for SSL,
handle_streammay be called before the SSL handshake has completed. Use
SSLIOStream.wait_for_handshakeif you need to verify the client’s certificate or use NPN/ALPN.
Changed in version 4.2: Added the option for this method to be a coroutine.