A Dart web server

The Dart VM can also run as a server application on the command line or as a background job. While creating the application, choose the command-line application template. Most of Dart's server functionality lives in the dart:io library, which cannot be used in writing browser Dart apps; in the same way, dart:html cannot be used on the server. The HttpServer class is used to write Dart servers; a server listens on a particular host and port for incoming requests and provides event handlers (also called request handlers) that are triggered when a request with incoming data from a client is received. The latter is described by the HttpRequest class, which is an asynchronous API provided by the browser (formerly known as Ajax) and has properties, such as method, path, query parameters, and InputStream with the data. The server responds by writing to OutputStream of an HttpResponse object. The following is the code of the webserver project, where you can easily see all the parts interacting:

import 'dart:io';

main() {
  print('simple web server'),
  HttpServer.bind('127.0.0.1', 8080).then((server) {
    print('server will start listening'),
    server.listen((HttpRequest request) {
      print('server listened'),
      request.response.write('Learn Dart by Projects, develop in Spirals!'),
      request.response.close();
    });
  });
}

Firstly, start the server from the editor or on the command line with dart webserver.dart. Then, start a (any) browser with the http://localhost:8080 URL to see the response text appear on the client; the print output will appear in the server console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.70.170