Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a web server


The class HttpServer is used to write web servers; this server listens on (or binds to) a particular host and port for incoming HTTP requests. It provides event handlers (better called request handlers in this case) that are triggered when a request with incoming data from a web client is received.

How to do it...

We make a project called simple_webserver starting from the template command-line application and import dart:io as follows:

import 'dart:io';
//Define host and port:
InternetAddress HOST = InternetAddress.LOOPBACK_IP_V6;
const int PORT = 8080;

main() {
  // Starting the web server:
  HttpServer.bind(HOST, PORT)
  .then((server) {
    print('server starts listening on port                          
	${server.port}');
    // Starting the request handler:
    server.listen(handleRequest);
  })
  .catchError(print);
}

handleRequest(HttpRequest req) {
  print('request coming in');
  req.response
  ..headers.contentType = new ContentType("text", "plain", charset...