A server that delivers content, such as web pages, using the HTTP protocol.
A server that delivers content, such as web pages, using the HTTP protocol.
The HttpServer is a Stream that provides HttpRequest objects. Each HttpRequest has an associated HttpResponse object. The server responds to a request by writing to that HttpResponse object. The following example shows how to bind an HttpServer to an IPv6 InternetAddress on port 80 (the standard port for HTTP servers) and how to listen for requests. Port 80 is the default HTTP port. However, on most systems accessing this requires super-user privileges. For local testing consider using a non-reserved port (1024 and above).
import 'dart:io';
main() {
HttpServer
.bind(InternetAddress.ANY_IP_V6, 80)
.then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}
Incomplete requests, in which all or part of the header is missing, are ignored, and no exceptions or HttpRequest objects are generated for them. Likewise, when writing to an HttpResponse, any Socket exceptions are ignored and any future writes are ignored.
The HttpRequest exposes the request headers and provides the request body, if it exists, as a Stream of data. If the body is unread, it is drained when the server writes to the HttpResponse or closes it.
Use bindSecure to create an HTTPS server.
The server presents a certificate to the client. In the following
example, the certificate is named localhost_cert
and comes from
the database found in the pkcert
directory.
import 'dart:io';
import "dart:isolate";
main() {
var testPkcertDatabase = Platform.script.resolve('pkcert')
.toFilePath();
SecureSocket.initialize(database: testPkcertDatabase,
password: 'dartdart');
HttpServer
.bindSecure(InternetAddress.ANY_IP_V6,
443,
certificateName: 'localhost_cert')
.then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}
The certificate database is managed using the Mozilla certutil tool (see NSS Tools certutil). Dart uses the NSS library to handle SSL, and the Mozilla certutil must be used to manipulate the certificate database.
You can use the listenOn constructor to attach an HTTP server to a ServerSocket.
import 'dart:io';
main() {
ServerSocket.bind(InternetAddress.ANY_IP_V6, 80)
.then((serverSocket) {
HttpServer httpserver = new HttpServer.listenOn(serverSocket);
serverSocket.listen((Socket socket) {
socket.write('Hello, client.');
});
});
}
HttpServer is a Stream. Refer to the Stream class for information about the streaming qualities of an HttpServer. Pausing the subscription of the stream, pauses at the OS level.
The http_server package on pub.dartlang.org contains a set of high-level classes that, together with this class, makes it easy to provide content through HTTP servers.