HttpServer class abstract
A server that delivers content, such as web pages, using the HTTP protocol.
Note: HttpServer provides low-level HTTP functionality. We recommend users evaluate the high-level APIs discussed at Write HTTP servers on dart.dev.
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';
void main() async {
var server = await HttpServer.bind(InternetAddress.anyIPv6, 80);
await server.forEach((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';
void main() async {
var chain =
Platform.script.resolve('certificates/server_chain.pem').toFilePath();
var key = Platform.script.resolve('certificates/server_key.pem').toFilePath();
var context = SecurityContext()
..useCertificateChain(chain)
..usePrivateKey(key, password: 'dartdart');
var server =
await HttpServer.bindSecure(InternetAddress.anyIPv6, 443, context);
await server.forEach((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.
- Implemented types
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
.factory
Properties
- address → InternetAddress
-
The address that the server is listening on.
no setter
- autoCompress ↔ bool
-
Whether the HttpServer should compress the content, if possible.
getter/setter pair
- defaultResponseHeaders → HttpHeaders
-
Default set of headers added to all response objects.
no setter
-
first
→ Future<
HttpRequest> -
The first element of this stream.
no setterinherited
- hashCode → int
-
The hash code for this object.
no setterinherited
- idleTimeout ↔ Duration?
-
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.
getter/setter pair
- isBroadcast → bool
-
Whether this stream is a broadcast stream.
no setterinherited
-
isEmpty
→ Future<
bool> -
Whether this stream contains any elements.
no setterinherited
-
last
→ Future<
HttpRequest> -
The last element of this stream.
no setterinherited
-
length
→ Future<
int> -
The number of elements in this stream.
no setterinherited
- port → int
-
The port that the server is listening on.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- serverHeader ↔ String?
-
Gets and sets the default value of the
Server
header for all responses generated by this HttpServer.getter/setter pair - sessionTimeout ← int
-
Sets the timeout, in seconds, for sessions of this HttpServer.
no getter
-
single
→ Future<
HttpRequest> -
The single element of this stream.
no setterinherited
Methods
-
any(
bool test(HttpRequest element)) → Future< bool> -
Checks whether
test
accepts any element provided by this stream.inherited -
asBroadcastStream(
{void onListen(StreamSubscription< HttpRequest> subscription)?, void onCancel(StreamSubscription<HttpRequest> subscription)?}) → Stream<HttpRequest> -
Returns a multi-subscription stream that produces the same events as this.
inherited
-
asyncExpand<
E> (Stream< E> ? convert(HttpRequest event)) → Stream<E> -
Transforms each element into a sequence of asynchronous events.
inherited
-
asyncMap<
E> (FutureOr< E> convert(HttpRequest event)) → Stream<E> -
Creates a new stream with each data event of this stream asynchronously
mapped to a new event.
inherited
-
cast<
R> () → Stream< R> -
Adapt this stream to be a
Stream<R>
.inherited -
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 - An HttpConnectionsInfo object summarizing the number of current connections handled by the server.
-
contains(
Object? needle) → Future< bool> -
Returns whether
needle
occurs in the elements provided by this stream.inherited -
distinct(
[bool equals(HttpRequest previous, HttpRequest next)?]) → Stream< HttpRequest> -
Skips data events if they are equal to the previous data event.
inherited
-
drain<
E> ([E? futureValue]) → Future< E> -
Discards all data on this stream, but signals when it is done or an error
occurred.
inherited
-
elementAt(
int index) → Future< HttpRequest> -
Returns the value of the
index
th data event of this stream.inherited -
every(
bool test(HttpRequest element)) → Future< bool> -
Checks whether
test
accepts all elements provided by this stream.inherited -
expand<
S> (Iterable< S> convert(HttpRequest element)) → Stream<S> -
Transforms each element of this stream into a sequence of elements.
inherited
-
firstWhere(
bool test(HttpRequest element), {HttpRequest orElse()?}) → Future< HttpRequest> -
Finds the first element of this stream matching
test
.inherited -
fold<
S> (S initialValue, S combine(S previous, HttpRequest element)) → Future< S> -
Combines a sequence of values by repeatedly applying
combine
.inherited -
forEach(
void action(HttpRequest element)) → Future< void> -
Executes
action
on each element of this stream.inherited -
handleError(
Function onError, {bool test(dynamic error)?}) → Stream< HttpRequest> -
Creates a wrapper Stream that intercepts some errors from this stream.
inherited
-
join(
[String separator = ""]) → Future< String> -
Combines the string representation of elements into a single string.
inherited
-
lastWhere(
bool test(HttpRequest element), {HttpRequest orElse()?}) → Future< HttpRequest> -
Finds the last element in this stream matching
test
.inherited -
listen(
void onData(HttpRequest event)?, {Function? onError, void onDone()?, bool? cancelOnError}) → StreamSubscription< HttpRequest> -
Adds a subscription to this stream.
inherited
-
map<
S> (S convert(HttpRequest event)) → Stream< S> -
Transforms each element of this stream into a new stream event.
inherited
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
pipe(
StreamConsumer< HttpRequest> streamConsumer) → Future -
Pipes the events of this stream into
streamConsumer
.inherited -
reduce(
HttpRequest combine(HttpRequest previous, HttpRequest element)) → Future< HttpRequest> -
Combines a sequence of values by repeatedly applying
combine
.inherited -
singleWhere(
bool test(HttpRequest element), {HttpRequest orElse()?}) → Future< HttpRequest> -
Finds the single element in this stream matching
test
.inherited -
skip(
int count) → Stream< HttpRequest> -
Skips the first
count
data events from this stream.inherited -
skipWhile(
bool test(HttpRequest element)) → Stream< HttpRequest> -
Skip data events from this stream while they are matched by
test
.inherited -
take(
int count) → Stream< HttpRequest> -
Provides at most the first
count
data events of this stream.inherited -
takeWhile(
bool test(HttpRequest element)) → Stream< HttpRequest> -
Forwards data events while
test
is successful.inherited -
timeout(
Duration timeLimit, {void onTimeout(EventSink< HttpRequest> sink)?}) → Stream<HttpRequest> -
Creates a new stream with the same events as this stream.
inherited
-
toList(
) → Future< List< HttpRequest> > -
Collects all elements of this stream in a List.
inherited
-
toSet(
) → Future< Set< HttpRequest> > -
Collects the data of this stream in a Set.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
-
transform<
S> (StreamTransformer< HttpRequest, S> streamTransformer) → Stream<S> -
Applies
streamTransformer
to this stream.inherited -
where(
bool test(HttpRequest event)) → Stream< HttpRequest> -
Creates a new stream from this stream that discards some elements.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
bind(
dynamic address, int port, {int backlog = 0, bool v6Only = false, }) → Future< HttpServer> -
Starts listening for HTTP requests on the specified
address
andport
. -
bindSecure(
dynamic address, int port, SecurityContext context, {int backlog = 0, bool v6Only = false, bool requestClientCertificate = false, }) → Future< HttpServer> -
The
address
can either be a String or an InternetAddress. Ifaddress
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.