HttpServer class

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.

Bind with a secure HTTPS connection

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.

Connect to a server socket

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.');
      });
    });
}

Other resources

Implements:

Constructors

HttpServer.listenOn ( ServerSocket serverSocket )
Attaches the HTTP server to an existing ServerSocket. When the HttpServer is closed, the HttpServer will just detach itself, closing current connections but not closing serverSocket.

Static Methods

bind ( address, int port, {int backlog: 0, bool v6Only: false, bool shared: false} ) → Future<HttpServer>
Starts listening for HTTP requests on the specified address and port.
bindSecure ( address, int port, {int backlog: 0, bool v6Only: false, String certificateName, bool requestClientCertificate: false, bool shared: false} ) → Future<HttpServer>
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopbac...

Instance Properties

serverHeader String
read/write
Get and set the default value of the Server header for all responses generated by this HttpServer.
autoCompress bool
read/write
Whether the HttpServer should compress the content, if possible.
idleTimeout Duration
read/write
Get or set the timeout used for idle keep-alive connections. If no further request is seen within idleTimeout after the previous request was completed, the connection is dropped.
defaultResponseHeaders HttpHeaders
read-only
port int
read-only
address InternetAddress
read-only
sessionTimeout int
write-only
isEmpty Future<bool> Inherited
read-only
isBroadcast bool Inherited
read-only
first Future<HttpRequest> Inherited
read-only
last Future<HttpRequest> Inherited
read-only
single Future<HttpRequest> Inherited
read-only
length Future<int> Inherited
read-only

Instance Methods

close ( {bool force: false} ) → Future
Permanently stops this HttpServer from listening for new connections. This closes the Stream of HttpRequests with a done event. The returned future completes when the server is stopped. For a s...
connectionsInfo ( ) → HttpConnectionsInfo
Returns an HttpConnectionsInfo object summarizing the number of current connections handled by the server.
pipe Inherited ( StreamConsumer<HttpRequest> streamConsumer ) → Future
Pipe the events of this stream into streamConsumer.
take Inherited ( int count ) → Stream<HttpRequest>
Provides at most the first n values of this stream.
map Inherited ( dynamic convert(T event) ) → Stream
Creates a new stream that converts each element of this stream to a new value using the convert function.
listen Inherited ( void onData(T event), {Function onError, void onDone(), bool cancelOnError} ) → StreamSubscription<HttpRequest>
Adds a subscription to this stream.
timeout Inherited ( Duration timeLimit, {void onTimeout(EventSink sink)} ) → Stream
Creates a new stream with the same events as this stream.
distinct Inherited ( [bool equals(T previous, T next)] ) → Stream<HttpRequest>
Skips data events if they are equal to the previous data event.
takeWhile Inherited ( bool test(T element) ) → Stream<HttpRequest>
Forwards data events while test is successful.
fold Inherited ( initialValue, dynamic combine(previous, T element) ) → Future
Reduces a sequence of values by repeatedly applying combine.
toSet Inherited ( ) → Future<Set<HttpRequest>>
Collects the data of this stream in a Set.
firstWhere Inherited ( bool test(T element), {Object defaultValue()} ) → Future
Finds the first element of this stream matching test.
forEach Inherited ( void action(T element) ) → Future
Executes action on each data event of the stream.
skipWhile Inherited ( bool test(T element) ) → Stream<HttpRequest>
Skip data events from this stream while they are matched by test.
join Inherited ( [String separator = ""] ) → Future<String>
Collects string of data events' string representations.
contains Inherited ( Object needle ) → Future<bool>
Checks whether needle occurs in the elements provided by this stream.
asyncExpand Inherited ( Stream convert(T event) ) → Stream
Creates a new stream with the events of a stream per original event.
lastWhere Inherited ( bool test(T element), {Object defaultValue()} ) → Future
Finds the last element in this stream matching test.
singleWhere Inherited ( bool test(T element) ) → Future<HttpRequest>
Finds the single element in this stream matching test.
drain Inherited ( [futureValue] ) → Future
Discards all data on the stream, but signals when it's done or an error occured.
asyncMap Inherited ( dynamic convert(T event) ) → Stream
Creates a new stream with each data event of this stream asynchronously mapped to a new event.
handleError Inherited ( Function onError, {bool test(error)} ) → Stream<HttpRequest>
Creates a wrapper Stream that intercepts some errors from this stream.
reduce Inherited ( T combine(T previous, T element) ) → Future<HttpRequest>
Reduces a sequence of values by repeatedly applying combine.
transform Inherited ( StreamTransformer<HttpRequest> streamTransformer ) → Stream
Chains this stream as the input of the provided StreamTransformer.
every Inherited ( bool test(T element) ) → Future<bool>
Checks whether test accepts all elements provided by this stream.
any Inherited ( bool test(T element) ) → Future<bool>
Checks whether test accepts any element provided by this stream.
toList Inherited ( ) → Future<List<HttpRequest>>
Collects the data of this stream in a List.
where Inherited ( bool test(T event) ) → Stream<HttpRequest>
Creates a new stream from this stream that discards some data events.
asBroadcastStream Inherited ( {void onListen(StreamSubscription<T> subscription), void onCancel(StreamSubscription<T> subscription)} ) → Stream<HttpRequest>
Returns a multi-subscription stream that produces the same events as this.
skip Inherited ( int count ) → Stream<HttpRequest>
Skips the first count data events from this stream.
expand Inherited ( Iterable convert(T value) ) → Stream
Creates a new stream from this stream that converts each element into zero or more events.
elementAt Inherited ( int index ) → Future<HttpRequest>
Returns the value of the indexth data event of this stream.