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

Using sockets


At a somewhat lower level in the OSI model than HTTP clients and servers, we find sockets. They also enable interprocess communications across a network between clients and servers and are implemented on top of the TCP/IP. The classes that offer that functionality can be again found in dart:io as follows:

  • Socket: This is used by a client to establish a connection to a server

  • ServerSocket: This is used by a server to accept client connections

How to do it...

The following steps will show you how to make a server socket work:

  1. The following is the code for the server (see the project sockets, socket_server.dart):

    import 'dart:io';
    import 'dart:convert';
    
    InternetAddress HOST = InternetAddress.LOOPBACK_IP_V6;
    const PORT = 7654;
    
    void main() {
      ServerSocket.bind(HOST, PORT)
      .then((ServerSocket srv) {
        print('serversocket is ready');
        srv.listen(handleClient);
        })
               .catchError(print);
      );
    }
    
    void handleClient(Socket client){
      print('Connection from: '
      '${client...