Dart Starting to In-depth Roadmap:

Dart Language — 45 minutes Quick Start (PART 1)

Dart Language — 45 minutes Quick Start (part 2)

Dart asynchronous programming in detail

Dart language asynchronous Stream details

Dart language standard flow and file manipulation

Dart Network programming

Dart crawler development experience

Dart full stack server development

Dart FFI calls C hybrid programming

Dart and Lua invocation in LuaDardo

Pay attention to me, not bad!

Dart Network programming

Dart code examples for network programming are provided below. Learn more about specific protocols.

TCP server

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

void main() {
  // bind port 8081 to localhost (i.e., bind: 127.0.0.1)
  ServerSocket.bind(InternetAddress.loopbackIPv4, 8081)
  .then((serverSocket) {
    serverSocket.listen((socket) {
      socket.cast<List<int>>().transform(utf8.decoder).listen(print);
    });
  });
}
Copy the code

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

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

void main() {
  startTCPServer();
}

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

  // Iterate over all sockets connected to the server
  await for(Socket socket in serverSocket) {
    // Decode the byte stream in UTF-8
    socket.cast<List<int>>().transform(utf8.decoder).listen((data) {
      print("from ${socket.remoteAddress.address} data:" + data);
      socket.add(utf8.encode('hello client! ')); }); }}Copy the code

TCP client

The corresponding concise expression is as follows

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

void main() {
  // Connect to port 8081 of 127.0.0.1
  Socket.connect('127.0.0.1'.8081).then((socket) {
    socket.write('Hello, Server! ');
    socket.cast<List<int>>().transform(utf8.decoder).listen(print);
  });
}
Copy the code

I can write it more clearly as follows

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

void main() {
  startTCPClient();
}

// TCP client
void startTCPClient() async {
  // Connect to port 8081 of the server
  Socket socket = await Socket.connect('127.0.0.1'.8081);
  socket.write('Hello, Server! ');
  socket.cast<List<int>>().transform(utf8.decoder).listen(print);
}
Copy the code

UDP server.

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

void main() {
  startUDPServer();
}

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

  // Listen for socket events
  await for (RawSocketEvent event in rawDgramSocket) {
    // The packet socket does not listen for data, but for events.
    // The receive function receives data only when the event is rawsocketevent. read
    if(event == RawSocketEvent.read) {
        print(utf8.decode(rawDgramSocket.receive().data));
        rawDgramSocket.send(utf8.encode("UDP Server:already received!"), InternetAddress.loopbackIPv4, 8082); }}}Copy the code

UDP client

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

void main() {
  startUDPClent();
}

// UDP client
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);

  // Listen for socket events
  await for (RawSocketEvent event in rawDgramSocket) {
    if(event == RawSocketEvent.read) {
        // Receive data
        print(utf8.decode(rawDgramSocket.receive().data)); }}}Copy the code

HTTP server and request

For more details on HTTP, please visit my blog

import 'dart:io';

void main() {
  HttpServer
      .bind(InternetAddress.loopbackIPv4, 8080)
      .then((server) {
        server.listen((HttpRequest request) {
         // Prints the requested path
          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(); }}); }); }Copy the code

The browser type http://localhost:8080/greet/zhangsan access

Now that you’re making a request to the server using the browser, let’s use code to simulate the browser making a request

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

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

  client.getUrl(Uri.parse("https://www.baidu.com/"))
    .then((HttpClientRequest request) {
      // Set the request header
      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) {
      // Process the response
      response.transform(utf8.decoder).listen((contents) {
        print(contents);
      });
    });
}
Copy the code

Typically, we don’t use the HTTP web request API provided by the Dart library directly, because the standard library is still too cumbersome to use and the third-party library is more concise and powerful. On Flutter, we mainly use the DIO library, which is very powerful. In addition, we can use the official HTTP library, which is even more concise. The link is shown below

  • http
  • dio

WebSocket

WebSocket is a protocol for full duplex communication over a single TCP connection. It makes it possible for both clients and servers to actively push messages, which can be text or binary data. And there is no same-origin policy restriction, there is no cross-domain problem. The identifier of the protocol is WS. Like HTTPS, WXS if it’s encrypted.

Websockets are standalone protocols created on top of TCP.

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

To create a Websocket connection, a request is made through the browser, and the server responds, a process often referred to as handshaking.

The service side

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 WebSocketTransformer to upgrade the request and listens for 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') {
      // Convert an HttpRequest to a WebSocket connection
      WebSocket socket = await WebSocketTransformer.upgrade(req);
      socket.listen((data) {
        print("from IP ${req.connectionInfo.remoteAddress.address}:${data}");
        socket.add("WebSocket Server:already received!"); }); }}}Copy the code

The client

import 'dart:io';

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

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

    // Close the connectionsocket.close(); }}Copy the code

Note: This article focuses on Dart programming examples. There are many issues to be addressed in the actual development of Flutter, such as TCP sticky packet issues, heartbeat mechanism, and using WebSocket with ProtoBuf in Dart.

Video course

Related video courses posted by bloggers

Dart Programming Guide for Flutter full stack development

Guide to the full stack development of Flutter


Follow my official account: The path of programming from 0 to 1