To create an HTTP server on a specific port in Rust, we can make use of the standard library's TcpListener
and TcpStream
to listen to incoming requests and send responses. Here's some sample code to create a basic server on port 8000:
main.rs578 chars20 lines
In this code, we first create a TcpListener
that listens on 127.0.0.1:8000
, which means it will only accept connections from the local machine on port 8000. Then, we loop through incoming connections with listener.incoming()
and read from the stream with stream.read()
. We then generate an HTTP response and write it back to the client with stream.write()
and stream.flush()
. The server will continue to run until it is interrupted, such as with a Ctrl+C
command.
Of course, this is just a basic example and a real-world HTTP server would require additional functionality, such as routing requests to the appropriate handlers, parsing headers and request bodies, and handling errors. However, this code should provide a starting point for creating an HTTP server in Rust.
gistlibby LogSnag