Dart network programming

Dart network programming

  • TCP server
  • TCP client
  • UDP server
  • UDP client
  • HTTP server and request
  • WebSocket
  • Server
  • Client

Dart network programming
The following provides various code examples of Dart's network programming. For specific protocol knowledge, please learn by yourself.

 

TCP server

import 'dart:convert';
import 'dart:io';

void main() {
  
  ServerSocket.bind(InternetAddress.loopbackIPv4, 8081)
  .then((serverSocket) {
    serverSocket.listen((socket) {
      socket.cast<List<int>>().transform(utf8.decoder).listen(print);
    });
  });
}

 

The above is a concise example, not very clear, equivalent to the following code

import 'dart:io';
import 'dart:convert';

void main() {
  startTCPServer();
}

//TCp

 

void startTCPServer() async{
  ServerSocket serverSocket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 8081);

 
  await for(Socket socket in serverSocket) {
   
    socket.cast<List<int>>().transform(utf8.decoder).listen((data) {
      print("from ${socket.remoteAddress.address} data:" + data);
      socket.add(utf8.encode('hello client!'));
    });
  }
}


TCP client
The corresponding concise expression is as follows

import 'dart:convert';
import 'dart:io';

void main() {
  
  Socket.connect('127.0.0.1', 8081).then((socket) {
    socket.write('Hello, Server!');
    socket.cast<List<int>>().transform(utf8.decoder).listen(print);
  });
}

import 'dart:convert';
import 'dart:io';

void main() {
  startTCPClient();
}

void startTCPClient() async {
  
  Socket socket = await Socket.connect('127.0.0.1', 8081);
  socket.write('Hello, Server!');
  socket.cast<List<int>>().transform(utf8.decoder).listen(print);
}

 

UDP server

import 'dart:io';
import 'dart:convert';

void main() {
  startUDPServer();
}

// UDP 
void startUDPServer() async {
  RawDatagramSocket rawDgramSocket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 8081);

 
  await for (RawSocketEvent event in rawDgramSocket) {
    
    if(event == RawSocketEvent.read) {
        print(utf8.decode(rawDgramSocket.receive().data));
        rawDgramSocket.send(utf8.encode("UDP Server:already received!"), InternetAddress.loopbackIPv4, 8082);
      }
  }
  }

 

UDP client

import 'dart:convert';
import 'dart:io';

void main() {
  startUDPClent();
}

// UDP
void startUDPClent() async {
   RawDatagramSocket rawDgramSocket = await RawDatagramSocket.bind('127.0.0.1', 8082);

   rawDgramSocket.send(utf8.encode("hello,world!"), InternetAddress('127.0.0.1'), 8081);

  
  await for (RawSocketEvent event in rawDgramSocket) {
    if(event == RawSocketEvent.read) {
        
        print(utf8.decode(rawDgramSocket.receive().data));
      }
  }
  }
  

 

 HTTP server and request

import 'dart:io';

void main() {
  HttpServer
      .bind(InternetAddress.loopbackIPv4, 8080)
      .then((server) {
        server.listen((HttpRequest request) {
         
          print(request.uri.path);
          if(request.uri.path.startsWith("/greet")){
            var subPathList = request.uri.path.split("/");

            if(subPathList.length >=3){
              request.response.write('Hello, ${subPathList[2]}');
              request.response.close();
            }else{
             request.response.write('Hello, ');
             request.response.close();
            }
          }else{
            request.response.write('Welcome to test server!');
            request.response.close();
          }
        });
      });
}

 

Browser input https://localhost:8080/greet/myaccess

The above is to use the browser to send a request to the server, then we use the code to simulate the browser to send the request

import 'dart:convert';
import 'dart:io';

void main() {
  HttpClient client = HttpClient();

  client.getUrl(Uri.parse("https://www.rrtutors.com/"))
    .then((HttpClientRequest request) {
      
      request.headers.add(HttpHeaders.userAgentHeader,
      "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
      return request.close();
    })
    .then((HttpClientResponse response) {

      response.transform(utf8.decoder).listen((contents) {
        print(contents);
      });
    });
}

 

Usually, we will not directly use the httpnetwork request API provided by the Dart standard library , because the standard library library is still too cumbersome to use, and the third-party library is more concise and powerful. On Flutter, the main use of the diolibrary, the function is very powerful, in addition can also use the official httplibrary, more concise and refined, the link is as follows

  • http
  • dio

WebSocket

WebSocket is a protocol for full-duplex communication on a single TCP connection . Its appearance allows both the client and the server to actively push messages, which can be text or binary data. And there is no limitation of the same-origin policy, and there is no cross-domain problem. The identifier of the agreement is . Like https if encrypted .wswxs

WebSocket is an independent protocol created on TCP.

Websocket handshake through the 101 status code of HTTP / 1.1 protocol.

In order to create a Websocket connection, a request needs to be sent through the browser, and then the server responds. This process is usually called "handshaking"

Server
The Web socket server uses a normal HTTP server to accept Web socket connections. The initial handshake is an HTTP request, which is then upgraded to a Web socket connection. The server uses the WebSocketTransformer upgrade request and listens to the data on the returned Web socket

 

import 'dart:io';

void main() async {
  HttpServer server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8083);
  await for (HttpRequest req in server) {
    if (req.uri.path == '/ws') {
     
      WebSocket socket = await WebSocketTransformer.upgrade(req);
      socket.listen((data) {
        print("from IP ${req.connectionInfo.remoteAddress.address}:${data}");
        socket.add("WebSocket Server:already received!");
      });
    }
  }
}

 

Client

import 'dart:io';

void main() async {
  WebSocket socket = await WebSocket.connect('ws://127.0.0.1:8083/ws');
  socket.add('Hello, World!');

  await for (var data in socket) {
    print("from Server: $data");

    
    socket.close();
  }
}