# Quick Tip: Write an HTTP server in Dart

In today’s quick tip, we will explore one of the inbuilt classes Dart gives us for creating web servers. This class comes as part of the “[**dart:io**](https://api.dartlang.org/dev/2.0.0-dev.68.0/dart-io/dart-io-library.html)” library in the SDK.

## Prefer a video?

%[https://www.youtube.com/watch?v=ko-urshBwU4] 

The class in particular is appropriately named `HttpServer`. Here’s how we’ll use it:

```dart
HttpServer.bind("localhost", 8080).then((HttpServer server) { ... });
```

`bind()` represents a static method that takes as required arguments a hostname and a port. This returns a `Future<HttpServer>`, allowing us to chain on methods like `then()` and `catch()`.

A successfully bound hostname and port now allows us to receive incoming requests by calling the `listen()` method on the server object, which has a `Stream`ing interface:

```dart
// ...
server.listen((HttpRequest request) {
  request.response.write('Hello world');
  request.response.close();
});
```

Receiving the request allows us to write out our response and end it. Here’s the full snippet in its glory:

```dart
import 'dart:io';

void main() {
  HttpServer
    .bind("localhost", 8080)
    .then((HttpServer server) {
      server.listen((HttpRequest request) {
        request.response.write("Hello world!");
        request.response.close();
      });
    });
}
```

## **Using Async/Await**

The above solution can be rendered in a much concise fashion using the **async/await** keywords:

```dart
import 'dart:io';

main() async {
  var server = await HttpServer.bind("localhost", 8080);

  await for (var request in server) {
    request.response.write("Hello world");
    request.response.close();
  }
}
```

Hope this was insightful.

**Like, share and** [**follow me**](https://twitter.com/creativ_bracket) ? for more content on Dart.

## **Quick links**

1. [HttpServer class](https://api.dartlang.org/stable/2.1.1/dart-io/HttpServer-class.html)
    
2. [**Free Dart screencasts on Egghead.io**](https://egghead.io/instructors/jermaine-oppong)
