TCP sockets

suggest change

TCP gives you a reliable, ordered, two-way stream of bytes between two programs. HTTP, SMTP, Redis, PostgreSQL and most other network protocols are built on top of it. When there's no ready-made client package for a protocol, or you design your own, you work with TCP sockets directly.

In Dart, TCP support is in dart:io, so it works in command-line programs, servers and Flutter apps on mobile and desktop, but not in the browser. The main classes are:

Class Role
ServerSocket listens on a port and gives you a Socket for each incoming connection
Socket one connection: a Stream<Uint8List> for reading and an IOSink for writing
ConnectionTask<Socket> a connection attempt in progress that you can cancel
SecureSocket, SecureServerSocket the same over TLS
RawSocket, RawServerSocket low-level, event-based sockets for special cases

This article covers:

The examples need no packages and were run with Dart 3.13 on Windows. All servers bind to 127.0.0.1 on port 0, which makes the OS pick a free port, so every example is a single self-contained program.

An echo server and client

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

Future<void> main() async {
  // Port 0 asks the OS for any free port.
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  print('listening on ${server.address.address}:${server.port}');

  server.listen((Socket client) {
    print('server: connection from '
        '${client.remoteAddress.address}:${client.remotePort}');
    // Echo every chunk of bytes back to the sender.
    client.listen(
      (data) => client.add(data),
      onDone: () {
        print('server: client closed its side');
        client.close();
      },
    );
  });

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  print('client: connected from local port ${socket.port}');

  socket.write('hello, TCP\n');
  await socket.flush();

  // Collect everything the server sends until it closes the connection.
  final reply = utf8.decoder.bind(socket).join();
  await socket.close(); // closes our sending side only
  print('client: got ${(await reply).trim()}');

  await server.close();
}

Output:

listening on 127.0.0.1:50617
server: connection from 127.0.0.1:50618
client: connected from local port 50618
server: client closed its side
client: got hello, TCP

The pieces:

Reading, writing and closing

A Socket is two things at once.

As a Stream<Uint8List> it delivers bytes as they arrive. You can listen to it, use await for, or pass it to decoders. A socket stream can be listened to only once.

As an IOSink it sends bytes:

Method What it does
add(List<int> bytes) queue raw bytes
write(Object? obj), writeln(...), writeAll(...) convert to a string and encode with socket.encoding (UTF-8 by default)
addStream(Stream<List<int>>) send a whole stream, respecting backpressure
flush() wait until queued data has been handed to the OS
close() flush, then close the sending direction
destroy() close both directions immediately, dropping queued data
done a future that completes when the sink is closed, or with an error if writing failed

add and write return immediately. Data is buffered and sent in the background. Errors from writing, such as the peer resetting the connection, show up on flush(), close() or done, not on write.

close() is a half-close: it tells the other side "I won't send anything more". The other side sees the end of its stream (onDone), but can still send to you, and you can still read. That's what the echo client does: it closes its side, the server sees onDone, closes its own side, and only then does the client's join() finish.

To read text, decode the bytes with utf8.decoder.bind(socket). The shorter socket.transform(utf8.decoder) doesn't compile, because a socket is a Stream<Uint8List> and utf8.decoder is a transformer from List<int>:

error - The argument type 'Utf8Decoder' can't be assigned to the parameter type
'StreamTransformer<Uint8List, dynamic>'.

decoder.bind(socket) works because a Stream<Uint8List> is a Stream<List<int>>. The other fix is socket.cast<List<int>>().transform(utf8.decoder).

utf8.decoder handles multi-byte characters split across chunks correctly. Decoding each chunk with utf8.decode(chunk) doesn't, and fails on any non-ASCII text sooner or later.

A write is not a message

TCP is a byte stream. It has no idea where your messages begin and end. The receiver may get several writes merged into one chunk, or one write split into many. This program writes three short strings and one 1 MB buffer, while the server is too busy to read at first:

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final done = Completer<void>();

  server.listen((client) async {
    // Pretend the server is busy, so data piles up in the OS buffer.
    await Future.delayed(const Duration(milliseconds: 200));
    var chunks = 0, total = 0;
    client.listen((Uint8List data) {
      chunks++;
      total += data.length;
      if (chunks == 1) print('server: first chunk: ${data.length} bytes');
    }, onDone: () {
      print('server: $total bytes in $chunks chunks');
      client.destroy();
      done.complete();
    });
  });

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  socket.write('first|');
  await socket.flush();
  socket.write('second|');
  await socket.flush();
  socket.write('third|');
  await socket.flush();
  socket.add(Uint8List(1000000)); // one big write
  await socket.close();
  socket.destroy();

  await done.future;
  await server.close();
}

Output from three runs:

server: first chunk: 131072 bytes
server: 1000019 bytes in 15 chunks
server: first chunk: 196608 bytes
server: 1000019 bytes in 13 chunks
server: first chunk: 131072 bytes
server: 1000019 bytes in 14 chunks

The three strings arrived glued together at the start of the first chunk, along with part of the big buffer, and the big buffer arrived in a different number of pieces each time. Over a real network the splits happen at even more arbitrary places.

So every protocol needs framing, a way to find message boundaries in the byte stream. The two common ones are:

A line-based protocol

For text protocols, LineSplitter from dart:convert does the framing. It buffers partial lines and emits whole ones, without the \n or \r\n.

The server below understands three commands. On the client side, StreamIterator turns the stream of lines into something you can pull from one line at a time, which suits a request/response protocol.

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

Future<void> handleClient(Socket socket) async {
  socket.writeln('WELCOME');
  final lines = utf8.decoder.bind(socket).transform(const LineSplitter());
  await for (final line in lines) {
    final parts = line.trim().split(RegExp(r'\s+'));
    switch (parts) {
      case ['ADD', final a, final b]:
        final sum = (int.tryParse(a) ?? 0) + (int.tryParse(b) ?? 0);
        socket.writeln('OK $sum');
      case ['UPPER', ...final words]:
        socket.writeln('OK ${words.join(' ').toUpperCase()}');
      case ['QUIT']:
        socket.writeln('BYE');
        await socket.close();
        return;
      default:
        socket.writeln('ERR unknown command: $line');
    }
  }
  // The client closed the connection without QUIT.
  await socket.close();
}

class LineClient {
  final Socket _socket;
  final StreamIterator<String> _lines;

  LineClient._(this._socket)
      : _lines = StreamIterator(
            utf8.decoder.bind(_socket).transform(const LineSplitter()));

  static Future<LineClient> connect(Object host, int port) async =>
      LineClient._(await Socket.connect(host, port));

  Future<String> readLine() async {
    if (!await _lines.moveNext()) {
      throw const SocketException('connection closed by server');
    }
    return _lines.current;
  }

  Future<String> request(String command) {
    _socket.writeln(command);
    return readLine();
  }

  Future<void> close() async {
    await _lines.cancel();
    _socket.destroy();
  }
}

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen(handleClient);

  final client = await LineClient.connect(InternetAddress.loopbackIPv4, server.port);
  print(await client.readLine());
  print(await client.request('ADD 2 40'));
  print(await client.request('UPPER zażółć gęślą jaźń'));
  print(await client.request('PING'));
  print(await client.request('QUIT'));
  await client.close();
  await server.close();
}

Output:

WELCOME
OK 42
OK ZAŻÓŁĆ GĘŚLĄ JAŹŃ
ERR unknown command: PING
BYE

Notes:

Length-prefixed binary messages

For binary data, or text that may contain newlines, put a length in front of each message. Here a frame is a 4-byte big-endian length followed by the payload. Encoding is easy. Decoding has to collect bytes until a whole frame is there, possibly finding several frames in one chunk.

On top of the framing, each payload is a JSON document, which gives a simple message protocol.

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

/// Prefixes [payload] with its length as a 4-byte big-endian integer.
Uint8List encodeFrame(List<int> payload) {
  final frame = Uint8List(4 + payload.length);
  ByteData.sublistView(frame).setUint32(0, payload.length);
  frame.setRange(4, frame.length, payload);
  return frame;
}

/// Turns a stream of arbitrary byte chunks into a stream of whole frames.
Stream<Uint8List> decodeFrames(Stream<List<int>> input,
    {int maxFrameLength = 1 << 20}) async* {
  final buffer = BytesBuilder(copy: false);
  var pending = Uint8List(0);

  await for (final chunk in input) {
    buffer
      ..add(pending)
      ..add(chunk);
    pending = buffer.takeBytes();

    var offset = 0;
    while (pending.length - offset >= 4) {
      final length = ByteData.sublistView(pending, offset).getUint32(0);
      if (length > maxFrameLength) {
        throw FormatException('frame too large: $length bytes');
      }
      if (pending.length - offset - 4 < length) break; // wait for more data
      yield Uint8List.sublistView(pending, offset + 4, offset + 4 + length);
      offset += 4 + length;
    }
    pending = Uint8List.sublistView(pending, offset);
  }
  if (pending.isNotEmpty) {
    throw FormatException('connection closed mid-frame '
        '(${pending.length} bytes left over)');
  }
}

void sendJson(Socket socket, Object? message) =>
    socket.add(encodeFrame(utf8.encode(jsonEncode(message))));

Stream<Object?> receiveJson(Socket socket) =>
    decodeFrames(socket).map((frame) => jsonDecode(utf8.decode(frame)));

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((socket) async {
    await for (final msg in receiveJson(socket)) {
      print('server got: $msg');
      if (msg case {'op': 'sum', 'values': List values}) {
        sendJson(socket, {'result': values.cast<num>().fold<num>(0, (a, b) => a + b)});
      }
    }
    await socket.close();
  });

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  final replies = StreamIterator(receiveJson(socket));

  sendJson(socket, {'op': 'sum', 'values': [1, 2, 3.5]});
  await replies.moveNext();
  print('client got: ${replies.current}');

  // Send a frame one byte at a time: the decoder still sees one message.
  final bytes = encodeFrame(utf8.encode(jsonEncode({'op': 'sum', 'values': [10, 20]})));
  for (final b in bytes) {
    socket.add([b]);
    await socket.flush();
  }
  await replies.moveNext();
  print('client got: ${replies.current}');

  await socket.close();
  await replies.cancel();
  await server.close();
}

Output:

server got: {op: sum, values: [1, 2, 3.5]}
client got: {result: 6.5}
server got: {op: sum, values: [10, 20]}
client got: {result: 30}

Things worth copying from this example:

For a richer binary format than raw JSON, put Protocol Buffers messages in the frames.

Serving many clients: a chat server

A server usually needs to know about all its connections, for example to broadcast. Keep them in a collection, and make sure each socket is removed however its connection ends: normal close, error, or server shutdown. try/finally around the read loop does that.

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

class ChatServer {
  final _clients = <Socket, String>{};
  late final ServerSocket _server;
  var _nextId = 1;

  Future<int> start() async {
    _server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
    _server.listen(_handle);
    return _server.port;
  }

  void _broadcast(String line, {Socket? except}) {
    for (final socket in _clients.keys) {
      if (socket != except) socket.writeln(line);
    }
  }

  Future<void> _handle(Socket socket) async {
    socket.setOption(SocketOption.tcpNoDelay, true);
    final name = 'user${_nextId++}';
    _clients[socket] = name;
    _broadcast('* $name joined', except: socket);

    try {
      await for (final line
          in utf8.decoder.bind(socket).transform(const LineSplitter())) {
        _broadcast('$name: $line', except: socket);
      }
    } on SocketException catch (e) {
      print('server: $name dropped: ${e.message}');
    } finally {
      _clients.remove(socket);
      socket.destroy();
      _broadcast('* $name left');
    }
  }

  Future<void> stop() async {
    await _server.close();
    for (final socket in _clients.keys.toList()) {
      socket.destroy();
    }
  }
}

Future<Socket> connectAndPrint(String label, int port) async {
  final socket = await Socket.connect(InternetAddress.loopbackIPv4, port);
  utf8.decoder
      .bind(socket)
      .transform(const LineSplitter())
      .listen((line) => print('[$label sees] $line'), onError: (_) {});
  return socket;
}

Future<void> pause() => Future.delayed(const Duration(milliseconds: 100));

Future<void> main() async {
  final chat = ChatServer();
  final port = await chat.start();

  final alice = await connectAndPrint('alice', port);
  await pause();
  final bob = await connectAndPrint('bob', port);
  await pause();

  alice.writeln('hi bob');
  await pause();
  bob.writeln('hello alice');
  await pause();

  bob.destroy();
  await pause();

  await chat.stop();
  alice.destroy();
}

Output:

[alice sees] * user2 joined
[bob sees] user1: hi bob
[alice sees] user2: hello alice
[alice sees] * user2 left

SocketOption.tcpNoDelay turns off Nagle's algorithm. Normally TCP briefly holds back small writes to combine them into fewer packets. For interactive protocols that send small messages and wait for replies, that delay hurts latency, so chat, game and RPC servers usually disable it. For bulk transfers leave it on.

The socket is removed from _clients before broadcasting "left", so the broadcast never writes to a socket that is already gone. Writes to a destroyed socket are silently dropped, but writing to a socket after calling close() on it throws StateError: StreamSink is closed, and an exception in the middle of the loop would break the broadcast for everyone else.

Errors and timeouts

Connection problems are reported as SocketException. Its message describes what failed and osError holds the operating system's error code.

import 'dart:async';
import 'dart:io';

Future<void> main() async {
  // 1. Nothing listens on the port: connection refused.
  final tmp = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final freePort = tmp.port;
  await tmp.close();
  try {
    await Socket.connect(InternetAddress.loopbackIPv4, freePort);
  } on SocketException catch (e) {
    print('refused: ${e.message}, errno ${e.osError?.errorCode}');
  }

  // 2. Unknown host name.
  try {
    await Socket.connect('no-such-host.invalid', 80);
  } on SocketException catch (e) {
    print('lookup: ${e.message}');
  }

  // 3. Host that never answers: give up after a timeout.
  final sw = Stopwatch()..start();
  try {
    await Socket.connect('10.255.255.1', 80,
        timeout: const Duration(seconds: 2));
  } on SocketException catch (e) {
    print('timeout after ${sw.elapsed.inSeconds}s: ${e.message}');
  }

  // 4. Port already in use.
  final a = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  try {
    await ServerSocket.bind(InternetAddress.loopbackIPv4, a.port);
  } on SocketException catch (e) {
    print('bind: ${e.message}, errno ${e.osError?.errorCode}');
  }
  await a.close();
}

Output on Windows:

refused: The remote computer refused the network connection, errno 1225
lookup: Failed host lookup: 'no-such-host.invalid'
timeout after 2s: Connection timed out, host: 10.255.255.1, port: 80
bind: Failed to create server socket, errno -1

Messages and error codes are platform-specific (on Linux, "connection refused" is errno 111, ECONNREFUSED), so don't build logic on the exact text.

Without timeout:, a connection to an unreachable host waits for the OS's own timeout, which can be more than 20 seconds on Windows and minutes on Linux. Always pass a timeout in clients.

Cancelling a connection attempt

Socket.startConnect returns a ConnectionTask right away. Its socket future completes when the connection is made, and cancel() aborts the attempt, which is what you want when a user presses "Cancel" or a screen is closed:

import 'dart:async';
import 'dart:io';

Future<void> main() async {
  final task = await Socket.startConnect('10.255.255.1', 80);
  // Cancel the attempt after 500 ms, e.g. because the user pressed "Cancel".
  Timer(const Duration(milliseconds: 500), task.cancel);
  try {
    await task.socket;
  } on SocketException catch (e) {
    print('cancelled: ${e.message}');
  }
}

Output:

cancelled: Connection attempt cancelled, host: InternetAddress('10.255.255.1', IPv4), port: 80

Idle timeouts

TCP doesn't notice by itself when the other side silently disappears (a pulled cable, a phone that lost signal). A connection with no traffic can look alive for hours. Servers should drop clients that stay quiet too long. Stream.timeout makes that a one-liner: it raises TimeoutException if the gap between two events is longer than the given duration.

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

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((socket) async {
    final lines = utf8.decoder
        .bind(socket)
        .transform(const LineSplitter())
        // Error if no line arrives within 300 ms of the previous one.
        .timeout(const Duration(milliseconds: 300));
    try {
      await for (final line in lines) {
        socket.writeln('echo: $line');
      }
    } on TimeoutException {
      socket.writeln('idle too long, bye');
      await socket.flush();
    }
    socket.destroy();
  });

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  final sw = Stopwatch()..start();
  final reader = utf8.decoder.bind(socket).transform(const LineSplitter()).listen(
      (line) => print('${sw.elapsedMilliseconds ~/ 100 * 100} ms: $line'));

  socket.writeln('one');
  await Future.delayed(const Duration(milliseconds: 200));
  socket.writeln('two');
  // Now go quiet. The server hangs up.
  await reader.asFuture<void>();
  print('connection closed by server');
  socket.destroy();
  await server.close();
}

Output:

0 ms: echo: one
200 ms: echo: two
500 ms: idle too long, bye
connection closed by server

Clients that need to keep an idle connection open send a small "ping" message every so often, and the protocol defines it. For more on timeouts in general see Cancellation and timeouts.

Large data and backpressure

add never blocks. If you call it in a loop faster than the network can send, the data piles up in memory. To send a large file or stream, use addStream, which reads from the source only as fast as the socket accepts data. On the receiving side, pipe does the reverse: it pauses the socket when the destination is slower.

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('tcp_demo');
  final source = File('${dir.path}/source.bin');
  await source.writeAsBytes(Uint8List(50 * 1024 * 1024)); // 50 MB
  final target = File('${dir.path}/received.bin');

  final received = Completer<void>();
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((socket) async {
    // pipe() pauses the socket when the file can't keep up, and closes
    // the file when the client closes its side.
    await socket.cast<List<int>>().pipe(target.openWrite());
    socket.destroy();
    received.complete();
  });

  final sw = Stopwatch()..start();
  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  // addStream() reads the file only as fast as the network accepts it.
  await socket.addStream(source.openRead());
  await socket.close();
  await received.future;
  socket.destroy();

  print('sent ${await source.length()} bytes, '
      'received ${await target.length()} bytes');
  print('took about ${sw.elapsedMilliseconds ~/ 100 * 100} ms');

  await server.close();
  await dir.delete(recursive: true);
}

Output:

sent 52428800 bytes, received 52428800 bytes
took about 300 ms

The cast<List<int>>() is needed for the same reason as with utf8.decoder: pipe on a Stream<Uint8List> wants a StreamConsumer<Uint8List>, and an IOSink is a StreamConsumer<List<int>>.

While addStream is running you must not call add or write on the same socket; that throws Bad state: StreamSink is bound to a stream. Wait for the returned future first.

Speaking an existing protocol: HTTP by hand

Sockets let you talk to any TCP server if you know the protocol. Here is an HTTP/1.1 request written by hand to a dart:io HttpServer. In real code use package:http (see HTTP Request), but seeing the raw exchange is useful when debugging.

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

Future<void> main() async {
  // A normal dart:io HTTP server to talk to.
  final http = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  http.listen((req) {
    req.response
      ..headers.contentType = ContentType.text
      ..write('hello from ${req.uri.path}\n')
      ..close();
  });

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, http.port);
  socket.setOption(SocketOption.tcpNoDelay, true);
  print('local  ${socket.address.address}:${socket.port}');
  print('remote ${socket.remoteAddress.address}:${socket.remotePort}');

  // HTTP/1.1 uses CRLF line endings; "Connection: close" makes the
  // server close the connection after the response, so we can read to EOF.
  socket.write('GET /raw HTTP/1.1\r\n'
      'Host: localhost\r\n'
      'Connection: close\r\n'
      '\r\n');

  final response = await utf8.decoder.bind(socket).join();
  print(response.replaceAll('\r\n', '\n'));
  socket.destroy();
  await http.close();
}

Output:

local  127.0.0.1:52288
remote 127.0.0.1:52287
HTTP/1.1 200 OK
connection: close
content-type: text/plain; charset=utf-8
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
transfer-encoding: chunked
x-content-type-options: nosniff

10
hello from /raw

0

The 10 and 0 lines are chunked transfer encoding: a chunk of 0x10 = 16 bytes, then the final empty chunk. Protocols have details like this, which is why a maintained client package is usually the better choice.

For TLS, SecureSocket.connect has the same API as Socket.connect and returns a SecureSocket, which is a Socket. SecureSocket.secure(socket) upgrades an existing plain connection, which is how STARTTLS in SMTP works. See TLS and HTTPS.

Using all CPU cores with shared: true

A Dart isolate runs on one thread. A busy server can spread connections over several isolates by having each one bind the same address and port with shared: true. The VM distributes incoming connections between them:

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

Future<void> serve(int id, int port) async {
  // Every isolate binds the same address and port with shared: true.
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, port,
      shared: true);
  await for (final socket in server) {
    socket.writeln('handled by isolate $id');
    await socket.close();
    socket.destroy();
  }
}

Future<void> main() async {
  // The first bind picks the port; the isolates share it.
  final first =
      await ServerSocket.bind(InternetAddress.loopbackIPv4, 0, shared: true);
  final port = first.port;
  first.listen((socket) {
    socket.writeln('handled by main isolate');
    socket.close().then((_) => socket.destroy());
  });

  for (var id = 1; id <= 3; id++) {
    await Isolate.spawn((_) => serve(id, port), null);
  }
  await Future.delayed(const Duration(milliseconds: 300));

  final counts = <String, int>{};
  for (var i = 0; i < 40; i++) {
    final s = await Socket.connect(InternetAddress.loopbackIPv4, port);
    final line = (await utf8.decoder.bind(s).join()).trim();
    counts[line] = (counts[line] ?? 0) + 1;
    s.destroy();
  }
  counts.forEach((k, v) => print('$k: $v'));
  exit(0); // stop the server isolates too
}

Output:

handled by main isolate: 10
handled by isolate 1: 10
handled by isolate 2: 10
handled by isolate 3: 10

Isolates don't share memory, so state like the chat server's client list can't simply be shared this way. See Isolates.

Common pitfalls

The program doesn't exit. An open socket keeps the Dart process alive. close() closes only the sending direction. If you never listen to the socket's stream, the receiving direction stays open and main finishing doesn't end the program:

import 'dart:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.listen(null, onDone: s.destroy));

  final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
  socket.write('bye');
  await socket.close(); // closes only the sending direction
  await server.close();
  print('main() finished');
  socket.destroy(); // without this line the program never exits
}

Output:

main() finished

Either consume the stream until it's done, or call destroy() when you're finished with a socket.

Other common mistakes:

Summary

Task How
Listen await ServerSocket.bind(InternetAddress.anyIPv4, port)
Pick a free port bind to port 0, read server.port
Accept connections server.listen((Socket s) { ... }) or await for (final s in server)
Connect await Socket.connect(host, port, timeout: Duration(seconds: 5))
Cancelable connect Socket.startConnect(...), then task.cancel()
Send bytes / text socket.add(bytes), socket.write(text)
Read text utf8.decoder.bind(socket)
Read lines .transform(const LineSplitter())
Request/response client StreamIterator over the decoded messages
Binary framing 4-byte length prefix with ByteData, buffer until complete
Send a large stream await socket.addStream(stream)
Lower latency for small messages socket.setOption(SocketOption.tcpNoDelay, true)
Idle timeout stream.timeout(duration)
Half-close await socket.close()
Close immediately socket.destroy()
TLS SecureSocket.connect, SecureServerSocket.bind
Use several cores ServerSocket.bind(..., shared: true) in several isolates

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents