dart:io
HttpServer class
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.anyIPv6, 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. The certificate chain and the private key are set in the SecurityContext object that is passed to bindSecure.
import 'dart:io';
import "dart:isolate";
main() {
SecurityContext context = new SecurityContext();
var chain =
Platform.script.resolve('certificates/server_chain.pem')
.toFilePath();
var key =
Platform.script.resolve('certificates/server_key.pem')
.toFilePath();
context.useCertificateChain(chain);
context.usePrivateKey(key, password: 'dartdart');
HttpServer
.bindSecure(InternetAddress.anyIPv6,
443,
context)
.then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}
The certificates and keys are PEM files, which can be created and managed with the tools in OpenSSL.
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.anyIPv6, 80)
.then((serverSocket) {
HttpServer httpserver = new HttpServer.listenOn(serverSocket);
serverSocket.listen((Socket socket) {
socket.write('Hello, client.');
});
});
}
Other resources
-
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 shelf 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.
- Implemented types
-
Constructors
- HttpServer.listenOn(ServerSocket serverSocket)
factory
- 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
.
Properties
- address → InternetAddress
read-only
- Returns the address that the server is listening on. This can be used to get the actual address used, when the address is fetched by a lookup from a hostname.
- autoCompress ↔ bool
read / write
- Whether the HttpServer should compress the content, if possible. [...]
- Default set of headers added to all response objects. [...]
- idleTimeout ↔ Duration
read / write
- Gets or sets 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. [...]
- port → int
read-only
- Returns the port that the server is listening on. This can be used to get the actual port used when a value of 0 for
port
is specified in the bind or bindSecure call. - Gets and sets the default value of the
Server
header for all responses generated by this HttpServer. [...] - sessionTimeout ← int
write-only
- Sets the timeout, in seconds, for sessions of this HttpServer. The default timeout is 20 minutes.
- first → Future<HttpRequest>
read-only, inherited
- The first element of this stream. [...]
- hashCode → int
read-only, inherited
- The hash code for this object. [...]
- isBroadcast → bool
read-only, inherited
- Whether this stream is a broadcast stream.
- isEmpty → Future<bool>
read-only, inherited
- Whether this stream contains any elements. [...]
- last → Future<HttpRequest>
read-only, inherited
- The last element of this stream. [...]
- length → Future<int>
read-only, inherited
- The number of elements in this stream. [...]
- runtimeType → Type
read-only, inherited
- A representation of the runtime type of the object.
- single → Future<HttpRequest>
read-only, inherited
- The single element of this stream. [...]
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 server started using bind or bindSecure this means that the port listened on no longer in use. [...]
- connectionsInfo() → HttpConnectionsInfo
- Returns an HttpConnectionsInfo object summarizing the number of current connections handled by the server.
- any(bool test(T element)) → Future<bool>
inherited
- Checks whether
test
accepts any element provided by this stream. [...] - asBroadcastStream({void onListen(StreamSubscription<T> subscription), void onCancel(StreamSubscription<T> subscription) }) → Stream<HttpRequest>
inherited
- Returns a multi-subscription stream that produces the same events as this. [...]
- asyncExpand<E>(Stream<E> convert(T event)) → Stream<E>
inherited
- Transforms each element into a sequence of asynchronous events. [...]
- asyncMap<E>(FutureOr<E> convert(T event)) → Stream<E>
inherited
- Creates a new stream with each data event of this stream asynchronously mapped to a new event. [...]
- cast<R>() → Stream<R>
inherited
- Adapt this stream to be a
Stream<R>
. [...] - contains(Object needle) → Future<bool>
inherited
- Returns whether
needle
occurs in the elements provided by this stream. [...] - distinct([bool equals(T previous, T next) ]) → Stream<HttpRequest>
inherited
- Skips data events if they are equal to the previous data event. [...]
- drain<E>([E futureValue ]) → Future<E>
inherited
- Discards all data on this stream, but signals when it is done or an error occurred. [...]
- elementAt(int index) → Future<HttpRequest>
inherited
- Returns the value of the
index
th data event of this stream. [...] - every(bool test(T element)) → Future<bool>
inherited
- Checks whether
test
accepts all elements provided by this stream. [...] - expand<S>(Iterable<S> convert(T element)) → Stream<S>
inherited
- Transforms each element of this stream into a sequence of elements. [...]
- firstWhere(bool test(T element), { HttpRequest orElse() }) → Future<HttpRequest>
inherited
- Finds the first element of this stream matching
test
. [...] - fold<S>(S initialValue, S combine(S previous, T element)) → Future<S>
inherited
- Combines a sequence of values by repeatedly applying
combine
. [...] - forEach(void action(T element)) → Future
inherited
- Executes
action
on each element of this stream. [...] - handleError(Function onError, { bool test(dynamic error) }) → Stream<HttpRequest>
inherited
- Creates a wrapper Stream that intercepts some errors from this stream. [...]
- join([String separator = "" ]) → Future<String>
inherited
- Combines the string representation of elements into a single string. [...]
- lastWhere(bool test(T element), { HttpRequest orElse() }) → Future<HttpRequest>
inherited
- Finds the last element in this stream matching
test
. [...] - listen(void onData(T event), { Function onError, void onDone(), bool cancelOnError }) → StreamSubscription<HttpRequest>
inherited
- Adds a subscription to this stream. [...]
- map<S>(S convert(T event)) → Stream<S>
inherited
- Transforms each element of this stream into a new stream event. [...]
- noSuchMethod(Invocation invocation) → dynamic
inherited
- Invoked when a non-existent method or property is accessed. [...]
- pipe(StreamConsumer<HttpRequest> streamConsumer) → Future
inherited
- Pipes the events of this stream into
streamConsumer
. [...] - reduce(HttpRequest combine(T previous, T element)) → Future<HttpRequest>
inherited
- Combines a sequence of values by repeatedly applying
combine
. [...] - singleWhere(bool test(T element), { HttpRequest orElse() }) → Future<HttpRequest>
inherited
- Finds the single element in this stream matching
test
. [...] - skip(int count) → Stream<HttpRequest>
inherited
- Skips the first
count
data events from this stream. [...] - skipWhile(bool test(T element)) → Stream<HttpRequest>
inherited
- Skip data events from this stream while they are matched by
test
. [...] - take(int count) → Stream<HttpRequest>
inherited
- Provides at most the first
count
data events of this stream. [...] - takeWhile(bool test(T element)) → Stream<HttpRequest>
inherited
- Forwards data events while
test
is successful. [...] - timeout(Duration timeLimit, { void onTimeout(EventSink<T> sink) }) → Stream<HttpRequest>
inherited
- Creates a new stream with the same events as this stream. [...]
- toList() → Future<List<HttpRequest>>
inherited
- Collects all elements of this stream in a List. [...]
- toSet() → Future<Set<HttpRequest>>
inherited
- Collects the data of this stream in a Set. [...]
- toString() → String
inherited
- Returns a string representation of this object.
- transform<S>(StreamTransformer<HttpRequest, S> streamTransformer) → Stream<S>
inherited
- Applies
streamTransformer
to this stream. [...] - where(bool test(T event)) → Stream<HttpRequest>
inherited
- Creates a new stream from this stream that discards some elements. [...]
Operators
- operator ==(dynamic other) → bool
inherited
- The equality operator. [...]
Static Methods
- bind(dynamic 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(dynamic address, int port, SecurityContext context, { int backlog: 0, bool v6Only: false, 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 loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface. [...]