RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Core libraries

Files, processes, sockets and HTTP

Files and directories, processes, standard input and output, sockets, an HTTP client and server, and WebSockets.

import 'raya:io';
106 classes598 functions and methods808 of 1,149 documented400 runnable examples

Overview

File, socket, HTTP, and other I/O support for non-web applications.

Important: Browser-based apps can't use this library. Only the following can import and use the raya:io library:

  • Servers
  • Command-line scripts
  • Evelyn mobile apps
  • Evelyn desktop apps

This library allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more. Many operations related to input and output are asynchronous and are handled using Futures or Streams, both of which are defined in the raya:async library.

To use the raya:io library in your code:

import 'raya:io';

File, Directory, and Link

An instance of File, Directory, or Link represents a file, directory, or link, respectively, in the native file system.

You can manipulate the file system through objects of these types. For example, you can rename a file or directory:

File myFile = File('myFile.txt');
myFile.rename('yourFile.txt').then((_) => print('file renamed'));

Many methods provided by the File, Directory, and Link classes run asynchronously and return a Future.

FileSystemEntity

File, Directory, and Link all extend FileSystemEntity. In addition to being the superclass for these classes, FileSystemEntity has a number of static methods for working with paths.

To get information about a path, you can use the FileSystemEntity static methods such as FileSystemEntity.isDirectory, FileSystemEntity.isFile, and FileSystemEntity.exists. Because file system access involves I/O, these methods are asynchronous and return a Future.

FileSystemEntity.isDirectory(myPath).then((isDir) {
  if (isDir) {
    print('$myPath is a directory');
  } else {
    print('$myPath is not a directory');
  }
});

HttpServer and HttpClient

The classes HttpClient and HttpServer provide low-level HTTP functionality.

Instead of using these classes directly, consider using more developer-friendly and composable APIs found in packages.

For HTTP clients, look at [package:http].

Process

The Process class provides a way to run a process on the native machine. For example, the following code spawns a process that recursively lists the files under web.

Process.start('ls', ['-R', 'web']).then((process) {
  stdout.addStream(process.stdout);
  stderr.addStream(process.stderr);
  process.exitCode.then(print);
});

Using Process.start returns a Future, which completes with a Process object when the process has started. This Process object allows you to interact with the process while it is running. Using Process.run returns a Future, which completes with a ProcessResult object when the spawned process has terminated. This ProcessResult object collects the output and exit code from the process.

When using Process.start, you need to read all data coming on the Process.stdout and Process.stderr streams, otherwise the system resources will not be freed.

WebSocket

The WebSocket class provides support for the web socket protocol. This allows full-duplex communications between client and server applications.

A web socket server uses a normal HTTP server for accepting web socket connections. The initial handshake is a HTTP request which is then upgraded to a web socket connection. The server upgrades the request using WebSocketTransformer and listens for the data on the returned web socket. For example, here's a mini server that listens for 'ws' data on a WebSocket:

runZoned(() async {
  var server = await HttpServer.bind('127.0.0.1', 4040);
  server.listen((HttpRequest req) async {
    if (req.uri.path == '/ws') {
      var socket = await WebSocketTransformer.upgrade(req);
      socket.listen(handleMsg);
    }
  });
}, onError: (e) => print("An error occurred."));

The client connects to the WebSocket using the WebSocket.connect method and a URI that uses the Web Socket protocol. The client can write to the WebSocket with the WebSocket.add method. For example,

var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws');
socket.add('Hello, World!');

Socket and ServerSocket

Clients and servers use Sockets to communicate using the TCP protocol. Use ServerSocket on the server side and Socket on the client. The server creates a listening socket using the bind method and then listens for incoming connections on the socket. For example:

ServerSocket.bind('127.0.0.1', 4041)
  .then((serverSocket) {
    serverSocket.listen((socket) {
      socket.transform(utf8.decoder).listen(print);
    });
  });

A client connects a Socket using the connect method, which returns a Future. Using write, writeln, or writeAll are the easiest ways to send data over the socket. For example:

Socket.connect('127.0.0.1', 4041).then((socket) {
  socket.write('Hello, World!');
});

Besides Socket and ServerSocket, the RawSocket and RawServerSocket classes are available for lower-level access to async socket IO.

Standard output, error, and input streams

This library provides the standard output, error, and input streams, named stdout, stderr, and stdin, respectively.

The stdout and stderr streams are both IOSinks and have the same set of methods and properties.

To write a string to stdout:

stdout.writeln('Hello, World!');

To write a list of objects to stderr:

stderr.writeAll([ 'That ', 'is ', 'an ', 'error.', '\n']);

The standard input stream is a true Stream, so it inherits properties and methods from the Stream class.

To read text synchronously from the command line (the program blocks waiting for user to type information):

String? inputText = stdin.readLineSync();

Functions and constants

Functions

exitfunction
Never exit(int code)

Exit the Raya VM process immediately with the given exit code.

This does not wait for any asynchronous operations to terminate nor execute finally blocks. Using exit is therefore very likely to lose data.

Child processes are not explicitly terminated (but they may terminate themselves when they detect that their parent has exited).

While debugging, the VM will not respect the --pause-isolates-on-exit flag if exit is called as invoking this method causes the Raya VM process to shutdown immediately. To properly break on exit, consider calling debugger from raya:developer or Isolate.pause from raya:isolate on Isolate.current to pause the isolate before invoking exit.

The handling of exit codes is platform specific.

On Linux and OS X an exit code for normal termination will always be in the range [0..255]. If an exit code outside this range is set the actual exit code will be the lower 8 bits masked off and treated as an unsigned value. E.g. Using an exit code of -1 will result in an actual exit code of 255 being reported.

On Windows the exit code can be set to any 32-bit value. However some of these values are reserved for reporting system errors like crashes.

Besides this the Raya executable itself uses an exit code of 254 for reporting compile time errors and an exit code of 255 for reporting runtime error (unhandled exception).

Due to these facts it is recommended to only use exit codes in the range \[0..127\] for communicating the result of running a Raya program to the surrounding environment. This will avoid any cross-platform issues.

Example
import 'raya:io';

void main() {
  // exit(code) ends the process at once, skipping pending work.
  // IOOverrides intercepts it here so the example can report the code.
  try {
    IOOverrides.runZoned(() {
      print('finishing work');
      exit(3);
    }, exit: (code) => throw 'exit($code) requested');
  } on String catch (msg) {
    print(msg);
  }
}
Output
finishing work
exit(3) requested
sleepfunction
void sleep(Duration duration)

Sleep for the duration specified in duration.

Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.

var duration = const Duration(seconds: 5);
print('Start sleeping');
sleep(duration);
print('5 seconds has passed');
Example
import 'raya:io';

void main() {
  print('before sleep');
  // Blocks the whole isolate: timers and I/O wait too.
  sleep(const Duration(milliseconds: 20));
  print('after sleeping 20 ms');
}
Output from the Raya VM
before sleep
after sleeping 20 ms
stdioTypefunction
StdioType stdioType(object)

Whether a stream is attached to a file, pipe, terminal, or something else.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final sink = File('${tmp.path}/out.txt').openWrite();
  print('a file sink: ${stdioType(sink)}');
  print('any other object: ${stdioType('text')}');
  await sink.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
a file sink: StdioType: file
any other object: StdioType: other

Constants and variables

zlibconstant
const ZLibCodec zlib = ZLibCodec._default()

An instance of the default implementation of the ZLibCodec.

gzipconstant
const GZipCodec gzip = GZipCodec._default()

An instance of the default implementation of the GZipCodec.

exitCodegetter
int get exitCode

Get the global exit code for the Raya VM.

The exit code is global for the Raya VM and the last assignment to exitCode from any isolate determines the exit code of the Raya VM on normal termination.

See exit for more information on how to chose a value for the exit code.

pidgetter
int get pid

Returns the PID of the current process.

stdingetter
Stdin get stdin

The standard input stream of data read by this program.

stdoutgetter
Stdout get stdout

The standard output stream of data written by this program.

The addError API is inherited from StreamSink and calling it will result in an unhandled asynchronous error unless there is an error handler on done.

stderrgetter
Stdout get stderr

The standard output stream of errors written by this program.

The addError API is inherited from StreamSink and calling it will result in an unhandled asynchronous error unless there is an error handler on done.

const SystemEncoding systemEncoding = const SystemEncoding()

The current system encoding.

This is used for converting from bytes to and from Strings when communicating on stdin, stdout and stderr.

On Windows this will use the currently active code page for the conversion. On all other systems it will always use UTF-8.

Typedefs

typedef BadCertificateCallback = bool Function(X509Certificate cr, String host, int port)

Classes

abstract class IOException implements Exception

Base class for all IO related exceptions.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

class QuotaException extends IOException {
  @override
  String toString() => 'QuotaException: disk quota reached';
}

void main() {
  print(QuotaException());
  print('FileSystemException is an IOException: ${FileSystemException() is IOException}');
}
Output
QuotaException: disk quota reached
FileSystemException is an IOException: true
class

OSError

class OSError implements Exception

An Exception holding information about an error from the operating system.

Constructors

OSErrorconstructor
const OSError([this.message = "", this.errorCode = noErrorCode])

Creates an OSError object from a message and an errorCode.

Example
import 'raya:io';

void main() {
  const e = OSError('No such file or directory', 2);
  print('message: ${e.message}, errorCode: ${e.errorCode}');
  print('no code: ${const OSError('unknown').errorCode == OSError.noErrorCode}');
}
Output
message: No such file or directory, errorCode: 2
no code: true

Static

noErrorCodeconstant
static const int noErrorCode = -1

Constant used to indicate that no OS error code is available.

Properties

messagefield
final String message

Error message supplied by the operating system. This will be empty if no message is associated with the error.

final int errorCode

Error code supplied by the operating system.

Will have the value OSError.noErrorCode if there is no error code associated with the error.

Methods

toStringmethod
String toString()

Converts an OSError object to a string representation.

Example
import 'raya:io';

void main() {
  print(const OSError('Permission denied', 13));
  print(const OSError('Something failed'));
}
Output
OS Error: Permission denied, errno = 13
OS Error: Something failed
abstract final class ZLibOption

Exposes ZLib options for input parameters.

See http://www.zlib.net/manual.html for more documentation.

Static

static const int minWindowBits = 8
static const int maxWindowBits = 15
static const int defaultWindowBits = 15
minLevelconstant
static const int minLevel = -1

Minimal value for ZLibCodec.level and ZLibEncoder.level.

maxLevelconstant
static const int maxLevel = 9

Maximal value for ZLibCodec.level and ZLibEncoder.level

defaultLevelconstant
static const int defaultLevel = 6

Default value for ZLibCodec.level and ZLibEncoder.level.

minMemLevelconstant
static const int minMemLevel = 1
maxMemLevelconstant
static const int maxMemLevel = 9
static const int defaultMemLevel = 8
static const int strategyFiltered = 1

Recommended strategy for data produced by a filter (or predictor)

static const int strategyHuffmanOnly = 2

Use this strategy to force Huffman encoding only (no string match)

strategyRleconstant
static const int strategyRle = 3

Use this strategy to limit match distances to one (run-length encoding)

static const int strategyFixed = 4

This strategy prevents the use of dynamic Huffman codes, allowing for a simpler decoder

static const int strategyDefault = 0

Recommended strategy for normal data

final class ZLibCodec extends Codec<List<int>, List<int>>

The ZLibCodec encodes raw bytes to ZLib compressed bytes and decodes ZLib compressed bytes to raw bytes.

Constructors

ZLibCodecconstructor
ZLibCodec({this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false, this.gzip = false})
Example
import 'raya:io';
import 'raya:convert';

void main() {
  final text = utf8.encode('na' * 200);
  final fast = ZLibCodec(level: 1), best = ZLibCodec(level: 9);
  print('raw ${text.length} bytes, level 1 -> ${fast.encode(text).length}, level 9 -> ${best.encode(text).length}');
  print('round trip ok: ${utf8.decode(best.decode(best.encode(text))) == 'na' * 200}');
}
Output from the Raya VM
raw 400 bytes, level 1 -> 15, level 9 -> 15
round trip ok: true

Properties

gzipfield
final bool gzip

When true, GZip frames will be added to the compressed data.

levelfield
final int level

The compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.

final int memLevel

Specifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.

The memory requirements for deflate are (in bytes):

(1 << (windowBits + 2)) +  (1 << (memLevel + 9))

That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)

final int strategy

Tunes the compression algorithm. Use the value strategyDefault for normal data, strategyFiltered for data produced by a filter (or predictor), strategyHuffmanOnly to force Huffman encoding only (no string match), or strategyRle to limit match distances to one (run-length encoding).

final int windowBits

Base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15

rawfield
final bool raw

When true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value

final List<int>? dictionary

Initial compression dictionary.

It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

encodergetter
ZLibEncoder get encoder

Get a ZLibEncoder for encoding to ZLib compressed data.

decodergetter
ZLibDecoder get decoder

Get a ZLibDecoder for decoding ZLib compressed data.

final class GZipCodec extends Codec<List<int>, List<int>>

The GZipCodec encodes raw bytes to GZip compressed bytes and decodes GZip compressed bytes to raw bytes.

Constructors

GZipCodecconstructor
GZipCodec({this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false, this.gzip = true})
Example
import 'raya:io';
import 'raya:convert';

void main() {
  final codec = GZipCodec(level: 6);
  final packed = codec.encode(utf8.encode('hello hello hello hello'));
  print('gzip magic bytes: ${packed.take(2).toList()} (0x1f 0x8b)');
  print('decoded: ${utf8.decode(codec.decode(packed))}');
}
Output from the Raya VM
gzip magic bytes: [31, 139] (0x1f 0x8b)
decoded: hello hello hello hello

Properties

gzipfield
final bool gzip

When true, GZip frames will be added to the compressed data.

levelfield
final int level

The compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.

final int memLevel

Specifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.

The memory requirements for deflate are (in bytes):

(1 << (windowBits + 2)) +  (1 << (memLevel + 9))

That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)

final int strategy

Tunes the compression algorithm. Use the value ZLibOption.strategyDefault for normal data, ZLibOption.strategyFiltered for data produced by a filter (or predictor), ZLibOption.strategyHuffmanOnly to force Huffman encoding only (no string match), or ZLibOption.strategyRle to limit match distances to one (run-length encoding).

final int windowBits

Base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15

final List<int>? dictionary

Initial compression dictionary.

It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

rawfield
final bool raw

When true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value

encodergetter
ZLibEncoder get encoder

Get a ZLibEncoder for encoding to GZip compressed data.

decodergetter
ZLibDecoder get decoder

Get a ZLibDecoder for decoding GZip compressed data.

final class ZLibEncoder extends Converter<List<int>, List<int>>

The ZLibEncoder encoder is used by ZLibCodec and GZipCodec to compress data.

Constructors

ZLibEncoderconstructor
ZLibEncoder({this.gzip = false, this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false})
Example
import 'raya:io';

void main() {
  final data = List.generate(1000, (i) => i % 10);
  final zlib = ZLibEncoder().convert(data);
  final gzip = ZLibEncoder(gzip: true).convert(data);
  final raw = ZLibEncoder(raw: true).convert(data);
  print('zlib header: ${zlib[0].toRadixString(16)}, gzip header: ${gzip[0].toRadixString(16)}');
  print('raw deflate is smallest: ${raw.length < zlib.length && zlib.length < gzip.length}');
}
Output from the Raya VM
zlib header: 78, gzip header: 1f
raw deflate is smallest: true

Properties

gzipfield
final bool gzip

When true, GZip frames will be added to the compressed data.

levelfield
final int level

The compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.

final int memLevel

Specifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.

The memory requirements for deflate are (in bytes):

(1 << (windowBits + 2)) +  (1 << (memLevel + 9))

That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)

final int strategy

Tunes the compression algorithm. Use the value ZLibOption.strategyDefault for normal data, ZLibOption.strategyFiltered for data produced by a filter (or predictor), ZLibOption.strategyHuffmanOnly to force Huffman encoding only (no string match), or ZLibOption.strategyRle to limit match distances to one (run-length encoding).

final int windowBits

Base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15

final List<int>? dictionary

Initial compression dictionary.

It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

rawfield
final bool raw

When true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value

Methods

convertmethod
List<int> convert(List<int> bytes)

Convert a list of bytes using the options given to the ZLibEncoder constructor.

Example
import 'raya:io';

void main() {
  final input = List.filled(4096, 65);
  final out = ZLibEncoder(level: 9).convert(input);
  print('4096 identical bytes compress to ${out.length < 50 ? 'under 50' : out.length} bytes');
  print('decodes back: ${zlib.decode(out).length}');
}
Output from the Raya VM
4096 identical bytes compress to under 50 bytes
decodes back: 4096
ByteConversionSink startChunkedConversion(Sink<List<int>> sink)

Start a chunked conversion using the options given to the ZLibEncoder constructor.

Accepts any Sink<List<int>>, but prefers a ByteConversionSink, and converts any other sink to a ByteConversionSink before using it.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final out = ByteConversionSink.withCallback((bytes) => print('decoded: ${utf8.decode(zlib.decode(bytes))}'));
  final sink = ZLibEncoder().startChunkedConversion(out);
  sink.add(utf8.encode('stream '));
  sink.add(utf8.encode('of chunks'));
  sink.close();
}
Output from the Raya VM
decoded: stream of chunks
final class ZLibDecoder extends Converter<List<int>, List<int>>

The ZLibDecoder is used by ZLibCodec and GZipCodec to decompress data.

Constructors

ZLibDecoderconstructor
ZLibDecoder({this.gzip = false, this.windowBits = ZLibOption.defaultWindowBits, this.dictionary, this.raw = false})
Example
import 'raya:io';
import 'raya:convert';

void main() {
  final gz = gzip.encode(utf8.encode('compressed with gzip'));
  print(utf8.decode(ZLibDecoder(gzip: true).convert(gz)));
  final raw = ZLibEncoder(raw: true).convert(utf8.encode('raw deflate'));
  print(utf8.decode(ZLibDecoder(raw: true).convert(raw)));
}
Output from the Raya VM
compressed with gzip
raw deflate

Properties

gzipfield
final bool gzip

When true, all concatenated compressed data sets in the input are decompressed and concatenated in the output.

final int windowBits

Base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15.

final List<int>? dictionary

Initial compression dictionary.

It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

rawfield
final bool raw

When true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value

Methods

convertmethod
List<int> convert(List<int> bytes)

Convert a list of bytes using the options given to the ZLibDecoder constructor.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final packed = zlib.encode(utf8.encode('Raya ' * 3));
  print('unpacked: ${utf8.decode(zlib.decoder.convert(packed))}');
  try {
    zlib.decoder.convert([1, 2, 3]);
  } on FormatException {
    print('not zlib data: FormatException');
  }
}
Output from the Raya VM
unpacked: Raya Raya Raya 
not zlib data: FormatException
ByteConversionSink startChunkedConversion(Sink<List<int>> sink)

Start a chunked conversion.

Accepts any Sink<List<int>>, but prefers a ByteConversionSink, and converts any other sink to a ByteConversionSink before using it.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final packed = zlib.encode(utf8.encode('split across two chunks'));
  final out = ByteConversionSink.withCallback((b) => print('decoded: ${utf8.decode(b)}'));
  final sink = zlib.decoder.startChunkedConversion(out);
  final mid = packed.length ~/ 2;
  sink.add(packed.sublist(0, mid));
  sink.add(packed.sublist(mid));
  sink.close();
}
Output from the Raya VM
decoded: split across two chunks
abstract interface class RawZLibFilter

The RawZLibFilter class provides a low-level interface to zlib.

Constructors

factory RawZLibFilter.deflateFilter({bool gzip = false, int level = ZLibOption.defaultLevel, int windowBits = ZLibOption.defaultWindowBits, int memLevel = ZLibOption.defaultMemLevel, int strategy = ZLibOption.strategyDefault, List<int>? dictionary, bool raw = false})

Returns a RawZLibFilter whose process and processed methods compress data.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final f = RawZLibFilter.deflateFilter(level: 9);
  final input = utf8.encode('abcabcabcabcabcabc');
  f.process(input, 0, input.length);
  final out = <int>[];
  for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
  print('deflated ${input.length} -> ${out.length} bytes; inflates to ${utf8.decode(zlib.decode(out))}');
}
Output from the Raya VM
deflated 18 -> 13 bytes; inflates to abcabcabcabcabcabc
factory RawZLibFilter.inflateFilter({bool gzip = false, int windowBits = ZLibOption.defaultWindowBits, List<int>? dictionary, bool raw = false})

Returns a RawZLibFilter whose process and processed methods decompress data.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final packed = zlib.encode(utf8.encode('filter me'));
  final f = RawZLibFilter.inflateFilter();
  f.process(packed, 0, packed.length);
  final out = <int>[];
  for (List<int>? c; (c = f.processed()) != null;) out.addAll(c!);
  print('inflated: ${utf8.decode(out)}');
}
Output from the Raya VM
inflated: filter me

Methods

processmethod
void process(List<int> data, int start, int end)

Process a chunk of data.

This method must only be called when processed returns null.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final f = RawZLibFilter.deflateFilter();
  final data = utf8.encode('xxhello worldxx');
  f.process(data, 2, 13); // only "hello world"
  final out = <int>[];
  for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
  print('compressed slice decodes to: ${utf8.decode(zlib.decode(out))}');
}
Output from the Raya VM
compressed slice decodes to: hello world
processedmethod
List<int>? processed({bool flush = true, bool end = false})

Get a chunk of processed data.

When there are no more data available, processed will return null. Set flush to false for non-final calls to improve performance of some filters.

The last call to processed should have end set to true. This will make sure an 'end' packet is written on the stream.

Example
import 'raya:io';

void main() {
  final f = RawZLibFilter.deflateFilter();
  final out = <int>[];
  // Even before any input the filter can hand out the 2-byte zlib header.
  final header = f.processed(flush: false)!;
  print('header: $header');
  out.addAll(header);
  f.process(List.filled(100, 7), 0, 100);
  // Call until it returns null; end: true finishes the stream.
  for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
  print('compressed to ${out.length} bytes; inflates to ${zlib.decode(out).length} bytes');
}
Output from the Raya VM
header: [120, 156]
compressed to 12 bytes; inflates to 100 bytes
abstract interface class Directory implements FileSystemEntity

A reference to a directory (or folder) on the file system.

A Directory is an object holding a path on which operations can be performed. The path to the directory can be absolute or relative. It allows access to the parent directory, since it is a FileSystemEntity.

The Directory also provides static access to the system's temporary file directory, systemTemp, and the ability to access and change the current directory.

Create a new Directory to give access the directory with the specified path:

var myDir = Directory('myDir');

Most instance methods of Directory exist in both synchronous and asynchronous variants, for example, create and createSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.

Create a directory

The following code sample creates a directory using the create method. By setting the recursive parameter to true, you can create the named directory and all its necessary parent directories, if they do not already exist.

import 'raya:io';

void main() async {
  // Creates dir/ and dir/subdir/.
  var directory = await Directory('dir/subdir').create(recursive: true);
  print(directory.path);
}
List the entries of a directory

Use the list or listSync methods to get the files and directories contained in a directory. Set recursive to true to recursively list all subdirectories. Set followLinks to true to follow symbolic links. The list method returns a Stream of FileSystemEntity objects. Listen on the stream to access each object as it is found:

import 'raya:io';

void main() async {
  // Get the system temp directory.
  var systemTempDir = Directory.systemTemp;

  // List directory contents, recursing into sub-directories,
  // but not following symbolic links.
  await for (var entity in
      systemTempDir.list(recursive: true, followLinks: false)) {
    print(entity.path);
  }
}
The use of asynchronous methods

I/O operations can block a program for some period of time while it waits for the operation to complete. To avoid this, all methods involving I/O have an asynchronous variant which returns a Future. This future completes when the I/O operation finishes. While the I/O operation is in progress, the Raya program is not blocked, and can perform other operations.

For example, the exists method, which determines whether the directory exists, returns a boolean value asynchronously using a Future.

import 'raya:io';

void main() async {
  final myDir = Directory('dir');
  var isThere = await myDir.exists();
  print(isThere ? 'exists' : 'nonexistent');
}

In addition to exists, the stat, rename, and other methods are also asynchronous.

Constructors

Directoryfactory
factory Directory(String path)

Creates a Directory object.

If path is a relative path, it will be interpreted relative to the current working directory (see Directory.current), when used.

If path is an absolute path, it will be immune to changes to the current working directory.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final dir = Directory('${tmp.path}/photos');
  print('exists: ${dir.existsSync()}');
  dir.createSync();
  print('exists after create: ${dir.existsSync()}');
  print('absolute: ${dir.isAbsolute}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
exists: false
exists after create: true
absolute: true
factory Directory.fromRawPath(Uint8List path)
Example
import 'raya:io';
import 'raya:convert';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final dir = Directory.fromRawPath(utf8.encode('${tmp.path}/résumés'))..createSync();
  print('name: ${dir.path.split('/').last}');
  print('exists: ${dir.existsSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
name: résumés
exists: true
factory Directory.fromUri(Uri uri)

Create a Directory from a URI.

If uri cannot reference a directory this throws UnsupportedError.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final dir = Directory.fromUri(tmp.uri.resolve('my%20dir/'))..createSync();
  print('name: ${dir.path.split('/').where((s) => s.isNotEmpty).last}');
  print('uri ends with slash: ${dir.uri.path.endsWith('/')}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
name: my dir
uri ends with slash: true

Static

currentstaticgetter
static Directory get current

Creates a directory object pointing to the current working directory.

currentstaticsetter
static void set current(dynamic path)

Sets the current working directory of the Raya process.

This affects all running isolates. The new value set can be either a Directory or a String.

The new value is passed to the OS's system call unchanged, so a relative path passed as the new working directory will be resolved by the OS.

Note that setting the current working directory is a synchronous operation and that it changes the working directory of all isolates.

Use this with care — especially when working with asynchronous operations and multiple isolates. Changing the working directory, while asynchronous operations are pending or when other isolates are working with the file system, can lead to unexpected results.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final before = Directory.current;
  Directory.current = tmp;
  File('relative.txt').writeAsStringSync('written relative to current');
  Directory.current = before;
  print('back to start: ${Directory.current.path == before.path}');
  print('file landed in tmp: ${File('${tmp.path}/relative.txt').existsSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
back to start: true
file landed in tmp: true
systemTempstaticgetter
static Directory get systemTemp

The system temp directory.

This is the directory provided by the operating system for creating temporary files and directories in. The location of the system temporary directory is platform-dependent, and may be controlled by an environment variable on some platforms.

Properties

pathgetter
String get path

Gets the path of this directory.

urigetter
Uri get uri

A Uri representing the directory's location.

The URI's scheme is always "file" if the entity's path is absolute, otherwise the scheme will be empty and the URI relative. The URI's path always ends in a slash ('/').

absolutegetter
Directory get absolute

A Directory whose path is the absolute path of this Directory.

The absolute path is computed by prefixing a relative path with the current working directory, or by returning an absolute path unchanged.

Methods

createmethod
Future<Directory> create({bool recursive = false})

Creates the directory if it doesn't exist.

If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.

Returns a Future<Directory> that completes with this directory once it has been created. If the directory cannot be created the future completes with an exception.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final deep = Directory('${tmp.path}/a/b/c');
  try {
    await deep.create();
  } on FileSystemException {
    print('create without recursive: fails (parent missing)');
  }
  await deep.create(recursive: true);
  print('create recursive: ${await deep.exists()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
create without recursive: fails (parent missing)
create recursive: true
void createSync({bool recursive = false})

Synchronously creates the directory if it doesn't exist.

If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.

If the directory cannot be created an exception is thrown.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  for (final p in ['src/lib', 'src/test', 'docs']) {
    Directory('${tmp.path}/$p').createSync(recursive: true);
  }
  Directory('${tmp.path}/docs').createSync(); // already there: no error
  final tree = tmp.listSync(recursive: true).map((e) => e.path.substring(tmp.path.length + 1)).toList()..sort();
  print('tree: $tree');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
tree: [docs, src, src/lib, src/test]
Future<Directory> createTemp([String? prefix])

Creates a temporary directory in this directory.

Additional random characters are appended to prefix to produce a unique directory name. If prefix is missing or null, the empty string is used as prefix.

Returns a Future<Directory> that completes with the newly created temporary directory.

Example
import 'raya:io';

Future<void> main() async {
  final work = await Directory.systemTemp.createTemp('job_');
  final name = work.path.split('/').last;
  print('prefix kept: ${name.startsWith('job_')}');
  print('unique suffix added: ${name.length > 'job_'.length}');
  await File('${work.path}/out.txt').writeAsString('ok');
  await work.delete(recursive: true);
  print('cleaned up: ${!await work.exists()}');
}
Output from the Raya VM
prefix kept: true
unique suffix added: true
cleaned up: true
Directory createTempSync([String? prefix])

Synchronously creates a temporary directory in this directory.

Additional random characters are appended to prefix to produce a unique directory name. If prefix is missing or null, the empty string is used as prefix.

Returns the newly created temporary directory.

Example
import 'raya:io';

void main() {
  final a = Directory.systemTemp.createTempSync('raya_ex_');
  final b = Directory.systemTemp.createTempSync('raya_ex_');
  print('two temp dirs differ: ${a.path != b.path}');
  final nested = a.createTempSync('inner');
  print('nested inside a: ${nested.parent.path == a.path}');
  a.deleteSync(recursive: true);
  b.deleteSync(recursive: true);
}
Output from the Raya VM
two temp dirs differ: true
nested inside a: true
String resolveSymbolicLinksSync()
Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final root = tmp.resolveSymbolicLinksSync();
  Directory('$root/v2/assets').createSync(recursive: true);
  Link('$root/current').createSync('v2');
  final p = Directory('$root/current/assets').resolveSymbolicLinksSync();
  print('current/assets -> ${p.substring(root.length + 1)}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
current/assets -> v2/assets
renamemethod
Future<Directory> rename(String newPath)

Renames this directory.

Returns a Future<Directory> that completes with a Directory for the renamed directory.

If newPath identifies an existing directory, then the behavior is platform-specific. On all platforms, the future completes with a FileSystemException if the existing directory is not empty. On POSIX systems, if newPath identifies an existing empty directory then that directory is deleted before this directory is renamed.

If newPath identifies an existing file or link, the operation fails and the future completes with a FileSystemException.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final draft = Directory('${tmp.path}/draft')..createSync();
  File('${draft.path}/page.txt').writeAsStringSync('p1');
  final published = await draft.rename('${tmp.path}/published');
  print('draft exists:     ${await draft.exists()}');
  print('published file:   ${File('${published.path}/page.txt').readAsStringSync()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
draft exists:     false
published file:   p1
Directory renameSync(String newPath)

Synchronously renames this directory.

Returns a Directory for the renamed directory.

If newPath identifies an existing directory, then the behavior is platform-specific. On all platforms, a FileSystemException is thrown if the existing directory is not empty. On POSIX systems, if newPath identifies an existing empty directory then that directory is deleted before this directory is renamed.

If newPath identifies an existing file or link the operation fails and a FileSystemException is thrown.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final a = Directory('${tmp.path}/a')..createSync();
  final b = a.renameSync('${tmp.path}/b');
  final names = tmp.listSync().map((e) => e.path.split('/').last).toList();
  print('after rename: $names');
  print('returned dir name: ${b.path.split('/').last}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
after rename: [b]
returned dir name: b
deletemethod
Future<FileSystemEntity> delete({bool recursive = false})

Deletes this Directory.

If recursive is false:

  • If path corresponds to an empty directory, then that directory is deleted. If path corresponds to a link, and that link resolves to a directory, then the link at path will be deleted. In all other cases, delete completes with a FileSystemException.

If recursive is true:

  • The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allows delete to be used to unconditionally delete any file system object.

If this Directory cannot be deleted, then delete completes with a FileSystemException.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final dir = Directory('${tmp.path}/cache')..createSync();
  File('${dir.path}/x').writeAsStringSync('x');
  try {
    await dir.delete();
  } on FileSystemException {
    print('non-empty, not recursive: fails');
  }
  await dir.delete(recursive: true);
  print('recursive delete: exists=${await dir.exists()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
non-empty, not recursive: fails
recursive delete: exists=false
void deleteSync({bool recursive = false})

Synchronously deletes this Directory.

If recursive is false:

  • If path corresponds to an empty directory, then that directory is deleted. If path corresponds to a link, and that link resolves to a directory, then the link at path will be deleted. In all other cases, delete throws a FileSystemException.

If recursive is true:

  • The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allows delete to be used to unconditionally delete any file system object.

If this Directory cannot be deleted, then delete throws a FileSystemException.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final empty = Directory('${tmp.path}/empty')..createSync();
  empty.deleteSync();
  print('empty dir deleted: ${!empty.existsSync()}');
  tmp.deleteSync(recursive: true);
  print('temp tree deleted: ${!tmp.existsSync()}');
}
Output from the Raya VM
empty dir deleted: true
temp tree deleted: true
listmethod
Stream<FileSystemEntity> list({bool recursive = false, bool followLinks = true})

Lists the sub-directories and files of this Directory.

Optionally recurses into sub-directories.

If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.

If followLinks is true, then working links are reported as directories or files, depending on what they point to, and links to directories are recursed into if recursive is true.

Broken links are reported as Link objects.

If a symbolic link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.

The result is a Stream of FileSystemEntity objects for the directories, files, and links. The Stream will be in an arbitrary order and does not include the special entries '.' and '..'.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  File('${tmp.path}/a.txt').writeAsStringSync('a');
  Directory('${tmp.path}/sub').createSync();
  File('${tmp.path}/sub/b.txt').writeAsStringSync('b');
  final top = <String>[], all = <String>[];
  await for (final e in tmp.list()) {
    top.add('${e.path.substring(tmp.path.length + 1)} (${e is Directory ? 'dir' : 'file'})');
  }
  await for (final e in tmp.list(recursive: true)) {
    all.add(e.path.substring(tmp.path.length + 1));
  }
  print('top level: ${top..sort()}');
  print('recursive: ${all..sort()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
top level: [a.txt (file), sub (dir)]
recursive: [a.txt, sub, sub/b.txt]
listSyncmethod
List<FileSystemEntity> listSync({bool recursive = false, bool followLinks = true})

Lists the sub-directories and files of this Directory. Optionally recurses into sub-directories.

If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.

If followLinks is true, then working links are reported as directories or files, depending on what they point to, and links to directories are recursed into if recursive is true.

Broken links are reported as Link objects.

If a link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.

Returns a List containing FileSystemEntity objects for the directories, files, and links. The List will be in an arbitrary order and does not include the special entries '.' and '..'.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  for (final n in ['b.ray', 'a.ray', 'notes.md']) {
    File('${tmp.path}/$n').writeAsStringSync(n);
  }
  final sources = tmp
      .listSync()
      .whereType<File>()
      .map((f) => f.path.split('/').last)
      .where((n) => n.endsWith('.ray'))
      .toList()
    ..sort();
  print('.ray files: $sources');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
.ray files: [a.ray, b.ray]
toStringmethod
String toString()

Returns a human readable representation of this Directory.

Example
import 'raya:io';

void main() {
  final dir = Directory('/data/projects');
  print('toString: $dir');
  print('path:     ${dir.path}');
  print('file:     ${File('notes.txt')}');
  print('link:     ${Link('latest')}');
}
Output
toString: Directory: '/data/projects'
path:     /data/projects
file:     File: 'notes.txt'
link:     Link: 'latest'
class FileMode

The modes in which a File can be opened.

Static

readconstant
static const read = FileMode._internal(0)

The mode for opening a file only for reading.

writeconstant
static const write = FileMode._internal(1)

Mode for opening a file for reading and writing. The file is overwritten if it already exists. The file is created if it does not already exist.

appendconstant
static const append = FileMode._internal(2)

Mode for opening a file for reading and writing to the end of it. The file is created if it does not already exist.

writeOnlyconstant
static const writeOnly = FileMode._internal(3)

Mode for opening a file for writing only. The file is overwritten if it already exists. The file is created if it does not already exist.

static const writeOnlyAppend = FileMode._internal(4)

Mode for opening a file for writing only to the end of it. The file is created if it does not already exist.

class FileLock

Type of lock when requesting a lock on a file.

Static

sharedconstant
static const shared = FileLock._internal(1)

Shared file lock.

exclusiveconstant
static const exclusive = FileLock._internal(2)

Exclusive file lock.

static const blockingShared = FileLock._internal(3)

Blocking shared file lock.

static const blockingExclusive = FileLock._internal(4)

Blocking exclusive file lock.

class

File

abstract interface class File implements FileSystemEntity

A reference to a file on the file system.

A File holds a path on which operations can be performed. You can get the parent directory of the file using parent, a property inherited from FileSystemEntity.

Create a new File object with a pathname to access the specified file on the file system from your program.

var myFile = File('file.txt');

The File class contains methods for manipulating files and their contents. Using methods in this class, you can open and close files, read to and write from them, create and delete them, and check for their existence.

When reading or writing a file, you can use streams (with openRead), random access operations (with open), or convenience methods such as readAsString,

Most methods in this class occur in synchronous and asynchronous pairs, for example, readAsString and readAsStringSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.

If path is a link

If path is a symbolic link, rather than a file, then the methods of File operate on the ultimate target of the link, except for delete and deleteSync, which operate on the link.

Read from a file

The following code sample reads the entire contents from a file as a string using the asynchronous readAsString method:

import 'raya:async';
import 'raya:io';

void main() {
  File('file.txt').readAsString().then((String contents) {
    print(contents);
  });
}

A more flexible and useful way to read a file is with a Stream. Open the file with openRead, which returns a stream that provides the data in the file as chunks of bytes. Read the stream to process the file contents when available. You can use various transformers in succession to manipulate the file content into the required format, or to prepare it for output.

You might want to use a stream to read large files, to manipulate the data with transformers, or for compatibility with another API, such as WebSockets.

import 'raya:io';
import 'raya:convert';
import 'raya:async';

void main() async {
  final file = File('file.txt');
  Stream<String> lines = file.openRead()
    .transform(utf8.decoder)       // Decode bytes to UTF-8.
    .transform(LineSplitter());    // Convert stream to individual lines.
  try {
    await for (var line in lines) {
      print('$line: ${line.length} characters');
    }
    print('File is now closed.');
  } catch (e) {
    print('Error: $e');
  }
}
Write to a file

To write a string to a file, use the writeAsString method:

import 'raya:io';

void main() async {
  final filename = 'file.txt';
  var file = await File(filename).writeAsString('some content');
  // Do something with the file.
}

You can also write to a file using a Stream. Open the file with openWrite, which returns an IOSink to which you can write data. Be sure to close the sink with the IOSink.close method.

import 'raya:io';

void main() async {
  var file = File('file.txt');
  var sink = file.openWrite();
  sink.write('FILE ACCESSED ${DateTime.now()}\n');
  await sink.flush();

  // Close the IOSink to free system resources.
  await sink.close();
}
The use of asynchronous methods

To avoid unintentional blocking of the program, several methods are asynchronous and return a Future. For example, the length method, which gets the length of a file, returns a Future. Wait for the future to get the result when it's ready.

import 'raya:io';

void main() async {
  final file = File('file.txt');

  var length = await file.length();
  print(length);
}

In addition to length, the exists, lastModified, stat, and other methods, are asynchronous.

Special 'nul' file

On Linux and Mac '/dev/null' and on Windows '\\?\NUL' refer to a special file, such that all writes to it get consumed and disappear, and all reads produce empty output. Note that on Windows 'nul'(without '\\?\'-prefix) refers to a regular file named 'nul' in current directory.

Constructors

Filefactory
factory File(String path)

Creates a File object.

If path is a relative path, it will be interpreted relative to the current working directory (see Directory.current), when used.

If path is an absolute path, it will be immune to changes to the current working directory.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/notes.txt');
  print('exists before write: ${file.existsSync()}');
  file.writeAsStringSync('hello');
  print('exists after write:  ${file.existsSync()}');
  print('name: ${file.uri.pathSegments.last}');
  print('parent is tmp: ${file.parent.path == tmp.path}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
exists before write: false
exists after write:  true
name: notes.txt
parent is tmp: true
factory File.fromUri(Uri uri)

Create a File object from a URI.

If uri cannot reference a file this throws UnsupportedError.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final uri = tmp.uri.resolve('data%20file.txt');
  final file = File.fromUri(uri);
  file.writeAsStringSync('from a uri');
  print('uri segment: ${uri.pathSegments.last}');
  print('file name:   ${file.path.split('/').last}');
  print('contents:    ${file.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
uri segment: data file.txt
file name:   data file.txt
contents:    from a uri
factory File.fromRawPath(Uint8List rawPath)

Creates a File object from a raw path.

A raw path is a sequence of bytes, as paths are represented by the OS.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raw = utf8.encode('${tmp.path}/café.txt');
  final file = File.fromRawPath(raw);
  file.writeAsStringSync('raw bytes path');
  print('name: ${file.path.split('/').last}');
  print('read: ${file.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
name: café.txt
read: raw bytes path

Properties

absolutegetter
File get absolute

A File with the absolute path of path.

The absolute path is computed by prefixing a relative path with the current working directory, or returning an absolute path unchanged.

pathgetter
String get path

Get the path of the file.

Methods

createmethod
Future<File> create({bool recursive = false, bool exclusive = false})

Creates the file.

Returns a Future<File> that completes with the file when it has been created.

If recursive is false, the default, the file is created only if all directories in its path already exist. If recursive is true, any non-existing parent paths are created first.

If exclusive is true and to-be-created file already exists, this operation completes the future with a PathExistsException.

If exclusive is false, existing files are left untouched by create. Calling create on an existing file still might fail if there are restrictive permissions on the file.

Completes the future with a FileSystemException if the operation fails.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a/b/c.txt');
  try {
    await file.create();
  } on FileSystemException catch (e) {
    print('without recursive: ${e.runtimeType}');
  }
  await file.create(recursive: true);
  print('with recursive:    ${await file.exists()}');
  print('empty length:      ${await file.length()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
without recursive: PathNotFoundException
with recursive:    true
empty length:      0
void createSync({bool recursive = false, bool exclusive = false})

Synchronously creates the file.

If recursive is false, the default, the file is created only if all directories in its path already exist. If recursive is true, all non-existing parent paths are created first.

If exclusive is true and to-be-created file already exists, then a FileSystemException is thrown.

If exclusive is false, existing files are left untouched by createSync. Calling createSync on an existing file still might fail if there are restrictive permissions on the file.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/logs/today.log')..createSync(recursive: true);
  print('created: ${file.existsSync()}, length ${file.lengthSync()}');
  file.writeAsStringSync('line 1\n');
  file.createSync(); // already exists: leaves contents alone
  print('after second create: ${file.readAsStringSync().trim()}');
  try {
    file.createSync(exclusive: true);
  } on FileSystemException {
    print('exclusive create fails when the file exists');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
created: true, length 0
after second create: line 1
exclusive create fails when the file exists
renamemethod
Future<File> rename(String newPath)

Renames this file.

Returns a Future<File> that completes with a File for the renamed file.

If newPath is a relative path, it is resolved against the current working directory (Directory.current). This means that simply changing the name of a file, but keeping it the original directory, requires creating a new complete path with the new name at the end. Example:

Future<File> changeFileNameOnly(File file, String newFileName) {
  var path = file.path;
  var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
  var newPath = path.substring(0, lastSeparator + 1) + newFileName;
  return file.rename(newPath);
}

On some platforms, a rename operation cannot move a file between different file systems. If that is the case, instead copy the file to the new location and then remove the original.

If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory, the operation fails and the future completes with a FileSystemException.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final draft = File('${tmp.path}/draft.txt')..writeAsStringSync('v1');
  final done = await draft.rename('${tmp.path}/final.txt');
  print('old exists: ${await draft.exists()}');
  print('new exists: ${await done.exists()}');
  print('new name:   ${done.path.split('/').last}, contents ${await done.readAsString()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
old exists: false
new exists: true
new name:   final.txt, contents v1
File renameSync(String newPath)

Synchronously renames this file.

Returns a File for the renamed file.

If newPath is a relative path, it is resolved against the current working directory (Directory.current). This means that simply changing the name of a file, but keeping it the original directory, requires creating a new complete path with the new name at the end. Example:

File changeFileNameOnlySync(File file, String newFileName) {
  var path = file.path;
  var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
  var newPath = path.substring(0, lastSeparator + 1) + newFileName;
  return file.renameSync(newPath);
}

On some platforms, a rename operation cannot move a file between different file systems. If that is the case, instead copySync the file to the new location and then deleteSync the original.

If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory the operation throws a FileSystemException.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final a = File('${tmp.path}/a.txt')..writeAsStringSync('A');
  final b = File('${tmp.path}/b.txt')..writeAsStringSync('B');
  // Renaming onto an existing file replaces it.
  a.renameSync(b.path);
  print('a exists: ${a.existsSync()}');
  print('b holds:  ${b.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
a exists: false
b holds:  A
deletemethod
Future<FileSystemEntity> delete({bool recursive = false})

Deletes this File.

If recursive is false:

  • If path corresponds to a regular file, named pipe or socket, then that path is deleted. If path corresponds to a link, and that link resolves to a file, then the link at path will be deleted. In all other cases, delete completes with a FileSystemException.

If recursive is true:

  • The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allows delete to be used to unconditionally delete any file system object.

If this File cannot be deleted, then delete completes with a FileSystemException.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/temp.bin')..writeAsBytesSync([1, 2, 3]);
  print('before: ${await file.exists()}');
  await file.delete();
  print('after:  ${await file.exists()}');
  try {
    await file.delete();
  } on PathNotFoundException {
    print('deleting again: PathNotFoundException');
  }
  await tmp.delete(recursive: true);
}
Output from the Raya VM
before: true
after:  false
deleting again: PathNotFoundException
void deleteSync({bool recursive = false})

Synchronously deletes this File.

If recursive is false:

  • If path corresponds to a regular file, named pipe or socket, then that path is deleted. If path corresponds to a link, and that link resolves to a file, then the link at path will be deleted. In all other cases, delete throws a FileSystemException.

If recursive is true:

  • The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allows delete to be used to unconditionally delete any file system object.

If this File cannot be deleted, then delete throws a FileSystemException.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  for (final n in ['a', 'b', 'c']) {
    File('${tmp.path}/$n.tmp').writeAsStringSync(n);
  }
  File('${tmp.path}/b.tmp').deleteSync();
  final left = tmp.listSync().map((e) => e.path.split('/').last).toList()..sort();
  print('left after deleting b.tmp: $left');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
left after deleting b.tmp: [a.tmp, c.tmp]
copymethod
Future<File> copy(String newPath)

Copies this file.

If newPath is a relative path, it is resolved against the current working directory (Directory.current).

Returns a Future<File> that completes with a File for the copied file.

If newPath identifies an existing file, that file is removed first. If newPath identifies an existing directory, the operation fails and the future completes with an exception.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final src = File('${tmp.path}/src.txt')..writeAsStringSync('original');
  final dst = await src.copy('${tmp.path}/dst.txt');
  await dst.writeAsString(' + edited', mode: FileMode.append);
  print('src: ${await src.readAsString()}');
  print('dst: ${await dst.readAsString()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
src: original
dst: original + edited
copySyncmethod
File copySync(String newPath)

Synchronously copies this file.

If newPath is a relative path, it is resolved against the current working directory (Directory.current).

Returns a File for the copied file.

If newPath identifies an existing file, that file is removed first. If newPath identifies an existing directory the operation fails and an exception is thrown.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final src = File('${tmp.path}/config.json')..writeAsStringSync('{"debug": false}');
  final backup = src.copySync('${tmp.path}/config.json.bak');
  src.writeAsStringSync('{"debug": true}');
  print('current: ${src.readAsStringSync()}');
  print('backup:  ${backup.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
current: {"debug": true}
backup:  {"debug": false}
lengthmethod
Future<int> length()

The length of the file.

Returns a Future<int> that completes with the length in bytes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/x.txt');
  await file.writeAsString('abc');
  print('ascii "abc":   ${await file.length()} bytes');
  await file.writeAsString('ééé');
  print('utf-8 "ééé":   ${await file.length()} bytes');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
ascii "abc":   3 bytes
utf-8 "ééé":   6 bytes
int lengthSync()

The length of the file provided synchronously.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/grow.bin')..writeAsBytesSync([]);
  for (var i = 1; i <= 3; i++) {
    file.writeAsBytesSync(List.filled(100, i), mode: FileMode.append);
    print('after append $i: ${file.lengthSync()} bytes');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
after append 1: 100 bytes
after append 2: 200 bytes
after append 3: 300 bytes
Future<DateTime> lastAccessed()

The last-accessed time of the file.

Returns a Future<DateTime> that completes with the date and time when the file was last accessed, if the information is available.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  await file.setLastAccessed(DateTime.utc(2024, 1, 2, 3, 4, 5));
  final t = (await file.lastAccessed()).toUtc();
  print('last accessed: ${t.toIso8601String()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
last accessed: 2024-01-02T03:04:05.000Z
DateTime lastAccessedSync()

The last-accessed time of the file.

Returns the date and time when the file was last accessed, if the information is available. Blocks until the information can be returned or it is determined that the information is not available.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  file.setLastAccessedSync(DateTime.utc(2000, 1, 1));
  print('year: ${file.lastAccessedSync().toUtc().year}');
  print('is before 2001: ${file.lastAccessedSync().isBefore(DateTime.utc(2001))}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
year: 2000
is before 2001: true
Future setLastAccessed(DateTime time)

Modifies the time the file was last accessed.

Returns a Future that completes once the operation has completed.

Throws a FileSystemException if the time cannot be set.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  final when = DateTime.utc(2023, 6, 15, 12);
  await file.setLastAccessed(when);
  print('set to:   ${when.toIso8601String()}');
  print('read back: ${(await file.lastAccessed()).toUtc().toIso8601String()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
set to:   2023-06-15T12:00:00.000Z
read back: 2023-06-15T12:00:00.000Z
void setLastAccessedSync(DateTime time)

Synchronously modifies the time the file was last accessed.

Throws a FileSystemException if the time cannot be set.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  file.setLastAccessedSync(DateTime.utc(1999, 12, 31, 23, 59, 59));
  print('accessed: ${file.lastAccessedSync().toUtc().toIso8601String()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
accessed: 1999-12-31T23:59:59.000Z
Future<DateTime> lastModified()

Get the last-modified time of the file.

Returns a Future<DateTime> that completes with the date and time when the file was last modified, if the information is available.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/report.txt')..writeAsStringSync('draft');
  await file.setLastModified(DateTime.utc(2024, 3, 1, 9, 30));
  final t = (await file.lastModified()).toUtc();
  print('modified: ${t.toIso8601String()}');
  print('weekday:  ${t.weekday}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
modified: 2024-03-01T09:30:00.000Z
weekday:  5
DateTime lastModifiedSync()

Get the last-modified time of the file.

Returns the date and time when the file was last modified, if the information is available. Blocks until the information can be returned or it is determined that the information is not available.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final old = File('${tmp.path}/old.txt')..writeAsStringSync('o');
  final fresh = File('${tmp.path}/new.txt')..writeAsStringSync('n');
  old.setLastModifiedSync(DateTime.utc(2020));
  fresh.setLastModifiedSync(DateTime.utc(2024));
  final newer = old.lastModifiedSync().isAfter(fresh.lastModifiedSync()) ? old : fresh;
  print('newer file: ${newer.path.split('/').last}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
newer file: new.txt
Future setLastModified(DateTime time)

Modifies the time the file was last modified.

Returns a Future that completes once the operation has completed.

Throws a FileSystemException if the time cannot be set.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  await file.setLastModified(DateTime.utc(2010, 10, 10, 10, 10, 10));
  print('modified: ${(await file.lastModified()).toUtc().toIso8601String()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
modified: 2010-10-10T10:10:10.000Z
void setLastModifiedSync(DateTime time)

Synchronously modifies the time the file was last modified.

If the attributes cannot be set, throws a FileSystemException.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
  file.setLastModifiedSync(DateTime.utc(2022, 2, 22));
  print('modified: ${file.lastModifiedSync().toUtc().toIso8601String()}');
  print('stat agrees: ${file.statSync().modified == file.lastModifiedSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
modified: 2022-02-22T00:00:00.000Z
stat agrees: true
openmethod
Future<RandomAccessFile> open({FileMode mode = FileMode.read})

Opens the file for random access operations.

Returns a Future<RandomAccessFile> that completes with the opened random access file. RandomAccessFiles must be closed using the RandomAccessFile.close method.

Files can be opened in three modes:

  • FileMode.write: open the file for both reading and writing and truncate the file to length zero. If the file does not exist the file is created.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/data.bin');
  final raf = await file.open(mode: FileMode.write);
  await raf.writeFrom([10, 20, 30, 40]);
  await raf.setPosition(1);
  print('byte at 1: ${await raf.readByte()}');
  await raf.close();
  print('file bytes: ${file.readAsBytesSync()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
byte at 1: 20
file bytes: [10, 20, 30, 40]
openSyncmethod
RandomAccessFile openSync({FileMode mode = FileMode.read})

Synchronously opens the file for random access operations.

The result is a RandomAccessFile on which random access operations can be performed. Opened RandomAccessFiles must be closed using the RandomAccessFile.close method.

See open for information on the mode argument.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/data.txt')..writeAsStringSync('0123456789');
  final raf = file.openSync(); // FileMode.read
  raf.setPositionSync(4);
  print('read 3 from 4: ${String.fromCharCodes(raf.readSync(3))}');
  print('position now:  ${raf.positionSync()}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
read 3 from 4: 456
position now:  7
openReadmethod
Stream<List<int>> openRead([int? start, int? end])

Creates a new independent Stream for the contents of this file.

If start is present, the file will be read from byte-offset start. Otherwise from the beginning (index 0).

If end is present, only bytes up to byte-index end will be read. Otherwise, until end of file.

In order to make sure that system resources are freed, the stream must be read to completion or the subscription on the stream must be cancelled.

If File is a named pipe then the returned Stream will wait until the write side of the pipe is closed before signaling "done". If there are no writers attached to the pipe when it is opened, then Stream.listen will wait until a writer opens the pipe.

An error opening or reading the file will appear as a FileSystemException error event on the returned Stream, after which the Stream is closed. For example:

// This example will print the "Error reading file" message and the
// `await for` loop will complete normally, without seeing any data
// events.
final stream = File('does-not-exist')
    .openRead()
    .handleError((e) => print('Error reading file: $e'));
await for (final data in stream) {
  print(data);
}
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/lines.txt')..writeAsStringSync('alpha\nbeta\ngamma\n');
  final lines = file.openRead().transform(utf8.decoder).transform(const LineSplitter());
  await for (final line in lines) {
    print('line: $line');
  }
  final middle = await file.openRead(6, 10).transform(utf8.decoder).join();
  print('bytes 6..10: $middle');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
line: alpha
line: beta
line: gamma
bytes 6..10: beta
openWritemethod
IOSink openWrite({FileMode mode = FileMode.write, Encoding encoding = utf8})

Creates a new independent IOSink for the file.

The IOSink must be closed when no longer used, to free system resources.

An IOSink for a file can be opened in two modes:

When writing strings through the returned IOSink the encoding specified using encoding will be used. The returned IOSink has an encoding property which can be changed after the IOSink has been created.

The returned IOSink does not transform newline characters ("\n") to the platform's conventional line ending (e.g. "\r\n" on Windows). Write a Platform.lineTerminator if a platform-specific line ending is needed.

If an error occurs while opening or writing to the file, the IOSink.done IOSink.flush, and IOSink.close futures will all complete with a FileSystemException. You must handle errors from the IOSink.done future or the error will be uncaught.

For example, FutureExtensions.ignore the IOSink.done error and remember to await the IOSink.flush and IOSink.close calls within a try/catch:

final sink = File('/tmp').openWrite(); // Can't write to /tmp
sink.done.ignore();
sink.write("This is a test");
try {
  // If one of these isn't awaited, then errors will pass silently!
  await sink.flush();
  await sink.close();
} on FileSystemException catch (e) {
  print('Error writing file: $e');
}

To handle errors asynchronously outside of the context of IOSink.flush and IOSink.close, you can Future.catchError the IOSink.done.

final sink = File('/tmp').openWrite(); // Can't write to /tmp
sink.done.catchError((e) {
 // Handle the error.
});
Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/out.csv');
  final sink = file.openWrite();
  sink.writeln('name,score');
  for (final (n, s) in [('ada', 9), ('alan', 8)]) {
    sink.writeln('$n,$s');
  }
  await sink.close();
  final more = file.openWrite(mode: FileMode.append)..write('grace,10\n');
  await more.close();
  print(file.readAsStringSync().trim());
  await tmp.delete(recursive: true);
}
Output from the Raya VM
name,score
ada,9
alan,8
grace,10
Future<Uint8List> readAsBytes()

Reads the entire file contents as a list of bytes.

Returns a Future<Uint8List> that completes with the list of bytes that is the contents of the file.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/b.bin');
  await file.writeAsBytes([0xCA, 0xFE, 0xBA, 0xBE]);
  final bytes = await file.readAsBytes();
  print('bytes: $bytes');
  print('hex:   ${bytes.map((b) => b.toRadixString(16)).join()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
bytes: [202, 254, 186, 190]
hex:   cafebabe
Uint8List readAsBytesSync()

Synchronously reads the entire file contents as a list of bytes.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/t.txt')..writeAsStringSync('Hié');
  final bytes = file.readAsBytesSync();
  print('bytes: $bytes');
  print('type:  ${bytes.runtimeType}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
bytes: [72, 105, 195, 169]
type:  Uint8List
Future<String> readAsString({Encoding encoding = utf8})

Reads the entire file contents as a string using the given Encoding.

Returns a Future<String> that completes with the string once the file contents has been read.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/t.txt');
  await file.writeAsString('naïve café');
  print('utf8:   ${await file.readAsString()}');
  print('latin1: ${await file.readAsString(encoding: latin1)}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
utf8:   naïve café
latin1: naïve café
String readAsStringSync({Encoding encoding = utf8})

Synchronously reads the entire file contents as a string using the given Encoding.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/config.ini')..writeAsStringSync('[main]\nwidth=80\n');
  final text = file.readAsStringSync();
  print('chars: ${text.length}');
  print('width: ${text.split('\n')[1].split('=')[1]}');
  try {
    File('${tmp.path}/missing.ini').readAsStringSync();
  } on PathNotFoundException {
    print('missing file: PathNotFoundException');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
chars: 16
width: 80
missing file: PathNotFoundException
Future<List<String>> readAsLines({Encoding encoding = utf8})

Reads the entire file contents as lines of text using the given Encoding.

Returns a Future<List<String>> that completes with the lines once the file contents has been read.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/todo.txt');
  await file.writeAsString('buy milk\r\nwrite docs\nship it');
  final lines = await file.readAsLines();
  print('count: ${lines.length}');
  for (final (i, l) in lines.indexed) {
    print('${i + 1}. $l');
  }
  await tmp.delete(recursive: true);
}
Output from the Raya VM
count: 3
1. buy milk
2. write docs
3. ship it
List<String> readAsLinesSync({Encoding encoding = utf8})

Synchronously reads the entire file contents as lines of text using the given Encoding.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/nums.txt')..writeAsStringSync('3\n14\n15\n92\n');
  final nums = file.readAsLinesSync().map(int.parse).toList();
  print('lines: $nums');
  print('sum:   ${nums.reduce((a, b) => a + b)}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
lines: [3, 14, 15, 92]
sum:   124
Future<File> writeAsBytes(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false})

Writes a list of bytes to a file.

Opens the file, writes the list of bytes to it, and closes the file. Returns a Future<File> that completes with this File object once the entire operation has completed.

By default writeAsBytes creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.

The elements of bytes should be integers in the range 0 to 255. Any integer, which is not in that range, is converted to a byte before being written. The conversion is equivalent to doing value.toUnsigned(8).

If the argument flush is set to true, the data written will be flushed to the file system before the returned future completes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/b.bin');
  await file.writeAsBytes([1, 2, 3]);
  await file.writeAsBytes([4, 5], mode: FileMode.append);
  print('appended: ${await file.readAsBytes()}');
  await file.writeAsBytes([9]);
  print('replaced: ${await file.readAsBytes()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
appended: [1, 2, 3, 4, 5]
replaced: [9]
void writeAsBytesSync(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false})

Synchronously writes a list of bytes to a file.

Opens the file, writes the list of bytes to it and closes the file.

By default writeAsBytesSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.

The elements of bytes should be integers in the range 0 to 255. Any integer, which is not in that range, is converted to a byte before being written. The conversion is equivalent to doing value.toUnsigned(8).

If the flush argument is set to true data written will be flushed to the file system before returning.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/ramp.bin');
  file.writeAsBytesSync([for (var i = 0; i < 8; i++) i * 32], flush: true);
  print('bytes:  ${file.readAsBytesSync()}');
  // Values are stored modulo 256.
  file.writeAsBytesSync([256, 257, -1]);
  print('wrapped: ${file.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
bytes:  [0, 32, 64, 96, 128, 160, 192, 224]
wrapped: [0, 1, 255]
Future<File> writeAsString(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false})

Writes a string to a file.

Opens the file, writes the string in the given encoding, and closes the file. Returns a Future<File> that completes with this File object once the entire operation has completed.

By default writeAsString creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.

If the argument flush is set to true, the data written will be flushed to the file system before the returned future completes.

This method does not transform newline characters ("\n") to the platform conventional line ending (e.g. "\r\n" on Windows). Use Platform.lineTerminator to separate lines in contents if platform conventional line endings are needed.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final log = File('${tmp.path}/app.log');
  for (final msg in ['start', 'work', 'stop']) {
    await log.writeAsString('$msg\n', mode: FileMode.append);
  }
  print(await log.readAsString());
  await tmp.delete(recursive: true);
}
Output from the Raya VM
start
work
stop
void writeAsStringSync(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false})

Synchronously writes a string to a file.

Opens the file, writes the string in the given encoding, and closes the file.

By default writeAsStringSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.

If the flush argument is set to true, data written will be flushed to the file system before returning.

This method does not transform newline characters ("\n") to the platform conventional line ending (e.g. "\r\n" on Windows). Use Platform.lineTerminator to separate lines in contents if platform conventional line endings are needed.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/t.txt');
  file.writeAsStringSync('été');
  print('utf8 bytes:   ${file.readAsBytesSync()}');
  file.writeAsStringSync('été', encoding: latin1);
  print('latin1 bytes: ${file.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
utf8 bytes:   [195, 169, 116, 195, 169]
latin1 bytes: [233, 116, 233]
abstract interface class RandomAccessFile

Random access to the data in a file.

RandomAccessFile objects are obtained by calling the open method on a File object.

A RandomAccessFile has both asynchronous and synchronous methods. The asynchronous methods all return a Future whereas the synchronous methods will return the result directly, and block the current isolate until the result is ready.

At most one asynchronous method can be pending on a given RandomAccessFile instance at the time. If another asynchronous method is called when one is already in progress, a FileSystemException is thrown.

If an asynchronous method is pending, it is also not possible to call any synchronous methods. This will also throw a FileSystemException.

Properties

pathgetter
String get path

The path of the file underlying this random access file.

Methods

closemethod
Future<void> close()

Closes the file.

Returns a Future that completes when it has been closed.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await File('${tmp.path}/a.bin').open(mode: FileMode.write);
  await raf.writeString('saved');
  await raf.close();
  print('content after close: ${File('${tmp.path}/a.bin').readAsStringSync()}');
  try {
    await raf.length();
  } on FileSystemException {
    print('using it after close: FileSystemException');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
content after close: saved
using it after close: FileSystemException
closeSyncmethod
void closeSync()

Synchronously closes the file.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/b.bin').openSync(mode: FileMode.write);
  raf.writeFromSync([1, 2, 3]);
  raf.closeSync();
  print('bytes on disk: ${File('${tmp.path}/b.bin').readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
bytes on disk: [1, 2, 3]
readBytemethod
Future<int> readByte()

Reads a byte from the file.

Returns a Future<int> that completes with the byte, or with -1 if end-of-file has been reached.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/c.txt')..writeAsStringSync('AB');
  final raf = await f.open();
  print('${await raf.readByte()}, ${await raf.readByte()}, ${await raf.readByte()} (-1 = end)');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
65, 66, -1 (-1 = end)
int readByteSync()

Synchronously reads a single byte from the file.

If end-of-file has been reached -1 is returned.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = (File('${tmp.path}/d.txt')..writeAsStringSync('hi!')).openSync();
  final bytes = <int>[];
  for (int b; (b = raf.readByteSync()) != -1;) bytes.add(b);
  print('bytes: $bytes -> ${String.fromCharCodes(bytes)}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
bytes: [104, 105, 33] -> hi!
readmethod
Future<Uint8List> read(int count)

Reads up to count bytes from a file.

May return fewer than count bytes. This can happen, for example, when reading past the end of a file or when reading from a pipe that does not currently contain additional data.

An empty Uint8List will only be returned when reading past the end of the file or when count is 0.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await (File('${tmp.path}/e.txt')..writeAsStringSync('0123456789')).open();
  print('read(4): ${String.fromCharCodes(await raf.read(4))}');
  print('read(4): ${String.fromCharCodes(await raf.read(4))}');
  print('read(4): ${String.fromCharCodes(await raf.read(4))} (only 2 left)');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
read(4): 0123
read(4): 4567
read(4): 89 (only 2 left)
readSyncmethod
Uint8List readSync(int count)

Synchronously reads up to count bytes from a file

May return fewer than count bytes. This can happen, for example, when reading past the end of a file or when reading from a pipe that does not currently contain additional data.

An empty Uint8List will only be returned when reading past the end of the file or when count is 0.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = (File('${tmp.path}/f.bin')..writeAsBytesSync([9, 8, 7, 6, 5])).openSync();
  raf.setPositionSync(2);
  print('readSync(2) from offset 2: ${raf.readSync(2)}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
readSync(2) from offset 2: [7, 6]
readIntomethod
Future<int> readInto(List<int> buffer, [int start = 0, int? end])

Reads bytes into an existing buffer.

Reads bytes and writes them into the range of buffer from start to end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Returns the number of bytes read. This maybe be less than end - start if the file doesn't have that many bytes to read.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await (File('${tmp.path}/g.bin')..writeAsBytesSync([1, 2, 3])).open();
  final buf = List.filled(6, 0);
  final n = await raf.readInto(buf, 2);
  print('read $n bytes into the buffer from index 2: $buf');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
read 3 bytes into the buffer from index 2: [0, 0, 1, 2, 3, 0]
int readIntoSync(List<int> buffer, [int start = 0, int? end])

Synchronously reads into an existing buffer.

Reads bytes and writes them into the range of buffer from start to end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Returns the number of bytes read. This maybe be less than end - start if the file doesn't have that many bytes to read.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';
import 'raya:typed_data';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = (File('${tmp.path}/h.bin')..writeAsBytesSync(List.generate(10, (i) => i))).openSync();
  final buf = Uint8List(4);
  var chunks = <List<int>>[];
  for (int n; (n = raf.readIntoSync(buf)) > 0;) chunks.add(buf.sublist(0, n));
  print('read in 4-byte chunks: $chunks');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
read in 4-byte chunks: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
writeBytemethod
Future<RandomAccessFile> writeByte(int value)

Writes a single byte to the file.

Returns a Future<RandomAccessFile> that completes with this random access file when the write completes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/i.bin');
  final raf = await f.open(mode: FileMode.write);
  for (final b in [0xCA, 0xFE]) {
    await raf.writeByte(b);
  }
  await raf.close();
  print('file bytes: ${f.readAsBytesSync().map((b) => b.toRadixString(16)).toList()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
file bytes: [ca, fe]
int writeByteSync(int value)

Synchronously writes a single byte to the file.

Returns 1 on success.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/j.txt');
  final raf = f.openSync(mode: FileMode.write);
  'OK\n'.codeUnits.forEach(raf.writeByteSync);
  raf.closeSync();
  print('file: ${f.readAsStringSync().trim()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
file: OK
writeFrommethod
Future<RandomAccessFile> writeFrom(List<int> buffer, [int start = 0, int? end])

Writes from a buffer to the file.

Will read the buffer from index start to index end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the write completes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/k.bin');
  final raf = await f.open(mode: FileMode.write);
  await raf.writeFrom([10, 20, 30, 40, 50], 1, 4);
  await raf.close();
  print('wrote bytes 1..4: ${f.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
wrote bytes 1..4: [20, 30, 40]
void writeFromSync(List<int> buffer, [int start = 0, int? end])

Synchronously writes from a buffer to the file.

Will read the buffer from index start to index end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/l.bin');
  final raf = f.openSync(mode: FileMode.write);
  raf.writeFromSync([1, 2, 3]);
  raf.writeFromSync([4, 5, 6], 1);
  raf.closeSync();
  print('file: ${f.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
file: [1, 2, 3, 5, 6]
Future<RandomAccessFile> writeString(String string, {Encoding encoding = utf8})

Writes a string to the file using the given Encoding.

Returns a Future<RandomAccessFile> that completes with this random access file when the write completes.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/m.txt');
  final raf = await f.open(mode: FileMode.write);
  await raf.writeString('café');
  print('utf8 length: ${await raf.length()}');
  await raf.setPosition(0);
  await raf.truncate(0);
  await raf.writeString('café', encoding: latin1);
  print('latin1 length: ${await raf.length()}');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
utf8 length: 5
latin1 length: 4
void writeStringSync(String string, {Encoding encoding = utf8})

Synchronously writes a single string to the file using the given Encoding.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/n.log');
  final raf = f.openSync(mode: FileMode.append);
  for (var i = 1; i <= 3; i++) {
    raf.writeStringSync('entry $i\n');
  }
  raf.closeSync();
  print(f.readAsLinesSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
[entry 1, entry 2, entry 3]
positionmethod
Future<int> position()

Gets the current byte position in the file.

Returns a Future<int> that completes with the position.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await (File('${tmp.path}/o.txt')..writeAsStringSync('abcdef')).open();
  print('start: ${await raf.position()}');
  await raf.read(4);
  print('after read(4): ${await raf.position()}');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
start: 0
after read(4): 4
int positionSync()

Synchronously gets the current byte position in the file.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/p.txt').openSync(mode: FileMode.write);
  raf.writeStringSync('hello');
  print('position after writing 5 bytes: ${raf.positionSync()}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
position after writing 5 bytes: 5
Future<RandomAccessFile> setPosition(int position)

Sets the byte position in the file.

Returns a Future<RandomAccessFile> that completes with this random access file when the position has been set.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/q.txt')..writeAsStringSync('hello world');
  final raf = await f.open();
  await raf.setPosition(6);
  print('from offset 6: ${String.fromCharCodes(await raf.read(5))}');
  await raf.setPosition(0);
  print('back to 0: ${String.fromCharCodes(await raf.read(5))}');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
from offset 6: world
back to 0: hello
void setPositionSync(int position)

Synchronously sets the byte position in the file.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/r.txt')..writeAsStringSync('hello world');
  final raf = f.openSync(mode: FileMode.write);
  raf.writeStringSync('hello world');
  raf.setPositionSync(6);
  raf.writeStringSync('WORLD');
  raf.closeSync();
  print(f.readAsStringSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
hello WORLD
truncatemethod
Future<RandomAccessFile> truncate(int length)

Truncates (or extends) the file to length bytes.

Returns a Future<RandomAccessFile> that completes with this random access file when the truncation has been performed.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/s.txt')..writeAsStringSync('keep|drop');
  final raf = await f.open(mode: FileMode.append);
  await raf.truncate(4);
  await raf.close();
  print('after truncate(4): ${f.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
after truncate(4): keep
void truncateSync(int length)

Synchronously truncates (or extends) the file to length bytes.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/t.bin');
  final raf = f.openSync(mode: FileMode.write);
  raf.truncateSync(8); // grows the file with zero bytes
  raf.closeSync();
  print('after truncateSync(8): ${f.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
after truncateSync(8): [0, 0, 0, 0, 0, 0, 0, 0]
lengthmethod
Future<int> length()

Gets the length of the file.

Returns a Future<int> that completes with the length in bytes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await File('${tmp.path}/u.txt').open(mode: FileMode.write);
  print('empty: ${await raf.length()}');
  await raf.writeString('twelve bytes');
  print('after writing: ${await raf.length()}');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
empty: 0
after writing: 12
int lengthSync()

Synchronously gets the length of the file.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = (File('${tmp.path}/v.bin')..writeAsBytesSync(List.filled(1024, 0))).openSync();
  print('lengthSync: ${raf.lengthSync()} bytes');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
lengthSync: 1024 bytes
flushmethod
Future<RandomAccessFile> flush()

Flushes the contents of the file to disk.

Returns a Future<RandomAccessFile> that completes with this random access file when the flush operation completes.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/w.txt');
  final raf = await f.open(mode: FileMode.write);
  await raf.writeString('durable');
  await raf.flush(); // pushed to the OS before close
  print('visible before close: ${f.readAsStringSync()}');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
visible before close: durable
flushSyncmethod
void flushSync()

Synchronously flushes the contents of the file to disk.

Throws a FileSystemException if the operation fails.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/x.txt');
  final raf = f.openSync(mode: FileMode.write);
  raf.writeStringSync('line 1\n');
  raf.flushSync();
  print('another reader sees: ${f.readAsStringSync().trim()}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
another reader sees: line 1
lockmethod
Future<RandomAccessFile> lock([FileLock mode = FileLock.exclusive, int start = 0, int end = -1])

Locks the file or part of the file.

By default an exclusive lock will be obtained, but that can be overridden by the mode argument.

Locks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is locked, If only start is specified the file is locked from byte position start to the end of the file, no matter how large it grows. It is possible to specify an explicit value of end which is past the current length of the file.

To obtain an exclusive lock on a file, it must be opened for writing.

If mode is FileLock.exclusive or FileLock.shared, an error is signaled if the lock cannot be obtained. If mode is FileLock.blockingExclusive or FileLock.blockingShared, the returned Future is resolved only when the lock has been obtained.

NOTE file locking does have slight differences in behavior across platforms:

On Linux and OS X this uses advisory locks, which have the surprising semantics that all locks associated with a given file are removed when any file descriptor for that file is closed by the process. Note that this does not actually lock the file for access. Also note that advisory locks are on a process level. This means that several isolates in the same process can obtain an exclusive lock on the same file.

On Windows the regions used for lock and unlock needs to match. If that is not the case unlocking will result in the OS error "The segment is already unlocked".

On Windows, locking a file associates the lock with the specific file handle used to acquire the lock. If the same file is opened again with a different handle (even within the same process), attempts to write to the locked region using the new handle will fail. To ensure successful writes after locking, use the same RandomAccessFile object that acquired the lock for subsequent write operations.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await File('${tmp.path}/app.lock').open(mode: FileMode.write);
  await raf.lock(FileLock.exclusive);
  print('holding an exclusive lock');
  await raf.writeString('pid file contents');
  await raf.unlock();
  print('released');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
holding an exclusive lock
released
lockSyncmethod
void lockSync([FileLock mode = FileLock.exclusive, int start = 0, int end = -1])

Synchronously locks the file or part of the file.

By default an exclusive lock will be obtained, but that can be overridden by the mode argument.

Locks the byte range from start to end of the file,with the byte at position end not included. If no arguments are specified, the full file is locked, If only start is specified the file is locked from byte position start to the end of the file, no matter how large it grows. It is possible to specify an explicit value of end which is past the current length of the file.

To obtain an exclusive lock on a file it must be opened for writing.

If mode is FileLock.exclusive or FileLock.shared, an exception is thrown if the lock cannot be obtained. If mode is FileLock.blockingExclusive or FileLock.blockingShared, the call returns only after the lock has been obtained.

NOTE file locking does have slight differences in behavior across platforms:

On Linux and OS X this uses advisory locks, which have the surprising semantics that all locks associated with a given file are removed when any file descriptor for that file is closed by the process. Note that this does not actually lock the file for access. Also note that advisory locks are on a process level. This means that several isolates in the same process can obtain an exclusive lock on the same file.

On Windows the regions used for lock and unlock needs to match. If that is not the case unlocking will result in the OS error "The segment is already unlocked".

On Windows, locking a file associates the lock with the specific file handle used to acquire the lock. If the same file is opened again with a different handle (even within the same process), attempts to write to the locked region using the new handle will fail. To ensure successful writes after locking, use the same RandomAccessFile object that acquired the lock for subsequent write operations.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/data.db').openSync(mode: FileMode.write);
  raf.writeFromSync(List.filled(100, 0));
  raf.lockSync(FileLock.shared, 0, 50); // lock only the first 50 bytes
  print('locked bytes 0..50 for shared reading');
  raf.unlockSync(0, 50);
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
locked bytes 0..50 for shared reading
unlockmethod
Future<RandomAccessFile> unlock([int start = 0, int end = -1])

Unlocks the file or part of the file.

Unlocks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is unlocked, If only start is specified the file is unlocked from byte position start to the end of the file.

NOTE file locking does have slight differences in behavior across platforms:

See lock for more details.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = await File('${tmp.path}/q.lock').open(mode: FileMode.write);
  await raf.lock(FileLock.blockingExclusive);
  print('locked');
  await raf.unlock();
  await raf.lock(FileLock.exclusive);
  print('unlocked and locked again');
  await raf.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
locked
unlocked and locked again
void unlockSync([int start = 0, int end = -1])

Synchronously unlocks the file or part of the file.

Unlocks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is unlocked, If only start is specified the file is unlocked from byte position start to the end of the file.

NOTE file locking does have slight differences in behavior across platforms:

See lockSync for more details.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/r.lock').openSync(mode: FileMode.write);
  raf.lockSync();
  raf.unlockSync();
  print('lockSync then unlockSync: ok');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
lockSync then unlockSync: ok
toStringmethod
String toString()

Returns a human-readable string for this random access file.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/notes.txt').openSync(mode: FileMode.write);
  print('toString: $raf');
  print('path: ${raf.path.replaceAll(tmp.path, '<tmp>')}');
  raf.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
toString: Instance of '_RandomAccessFile'
path: <tmp>/notes.txt
class FileSystemException implements IOException

Exception thrown when a file operation fails.

Constructors

const FileSystemException([this.message = "", this.path = "", this.osError])

Creates a new file system exception with optional parts.

Creates an exception with FileSystemException.message, FileSystemException.path and FileSystemException.osError values take from the optional parameters of the same name.

The message and path path defaults to empty strings if omitted, and osError defaults to null.

Example
import 'raya:io';

void main() {
  const e = FileSystemException('Cannot open', 'config.yaml', OSError('No such file or directory', 2));
  print('message: ${e.message}, path: ${e.path}, errno: ${e.osError?.errorCode}');
  try {
    File('definitely/missing/file.txt').readAsStringSync();
  } on FileSystemException catch (e) {
    print('caught for path: ${e.path}');
  }
}
Output from the Raya VM
message: Cannot open, path: config.yaml, errno: 2
caught for path: definitely/missing/file.txt

Properties

messagefield
final String message

Message describing the error.

The message does not include any detailed information from the underlying OS error. Check osError for that information.

pathfield
final String? path

The file system path on which the error occurred.

Can be null if the exception does not relate directly to a file system path.

osErrorfield
final OSError? osError

The underlying OS error.

Can be null if the exception is not raised due to an OS error.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const FileSystemException('Cannot delete', 'a.txt'));
  print(const FileSystemException('Cannot read', 'b.txt', OSError('Permission denied', 13)));
}
Output
FileSystemException: Cannot delete, path = 'a.txt'
FileSystemException: Cannot read, path = 'b.txt' (OS Error: Permission denied, errno = 13)
class PathAccessException extends FileSystemException

Exception thrown when a file operation fails because the necessary access rights are not available.

Constructors

const PathAccessException(String path, OSError osError, [String message = ""])
Example
import 'raya:io';

void main() {
  const e = PathAccessException('/root/secret', OSError('Permission denied', 13), 'Cannot open file');
  print('is a FileSystemException: ${e is FileSystemException}');
  print('path: ${e.path}, errno: ${e.osError!.errorCode}');
}
Output
is a FileSystemException: true
path: /root/secret, errno: 13

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const PathAccessException('locked.txt', OSError('Permission denied', 13), 'Cannot write'));
}
Output
PathAccessException: Cannot write, path = 'locked.txt' (OS Error: Permission denied, errno = 13)
class PathExistsException extends FileSystemException

Exception thrown when a file operation fails because the target path already exists.

Constructors

const PathExistsException(String path, OSError osError, [String message = ""])
Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final d = Directory('${tmp.path}/x')..createSync();
  try {
    File(d.path).createSync(exclusive: true);
  } on FileSystemException catch (e) {
    print('creating over an existing path: ${e.runtimeType}');
  }
  print(const PathExistsException('x', OSError('File exists', 17)).path);
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
creating over an existing path: PathExistsException
x

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const PathExistsException('out', OSError('File exists', 17), 'Creation failed'));
}
Output
PathExistsException: Creation failed, path = 'out' (OS Error: File exists, errno = 17)
class PathNotFoundException extends FileSystemException

Exception thrown when a file operation fails because a file or directory does not exist.

Constructors

const PathNotFoundException(String path, OSError osError, [String message = ""])
Example
import 'raya:io';

void main() {
  try {
    File('no/such/file.txt').readAsStringSync();
  } on PathNotFoundException catch (e) {
    print('PathNotFoundException for ${e.path}, errno ${e.osError?.errorCode}');
  }
}
Output from the Raya VM
PathNotFoundException for no/such/file.txt, errno 2

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const PathNotFoundException('missing.txt', OSError('No such file or directory', 2), 'Cannot open file'));
}
Output
PathNotFoundException: Cannot open file, path = 'missing.txt' (OS Error: No such file or directory, errno = 2)
abstract interface class ReadPipe implements Stream<List<int>>

The "read" end of an Pipe created by Pipe.create.

The read stream will continue to listen until the "write" end of the pipe (i.e. Pipe.write) is closed.

final pipe = await Pipe.create();
pipe.read.transform(utf8.decoder).listen((data) {
  print(data);
}, onDone: () => print('Done'));
abstract interface class WritePipe implements IOSink

The "write" end of an Pipe created by Pipe.create.

final pipe = await Pipe.create();
pipe.write.add("Hello World!".codeUnits);
await pipe.write.flush();
await pipe.write.close();
class

Pipe

abstract interface class Pipe

An anonymous pipe that can be used to send data in a single direction i.e. data written to write can be read using read.

On macOS and Linux (excluding Android), either the read or write portion of the pipe can be transmitted to another process and used for interprocess communication.

For example:

final pipe = await Pipe.create();
final socket = await RawSocket.connect(address, 0);
socket.sendMessage(<SocketControlMessage>[
SocketControlMessage.fromHandles(
    <ResourceHandle>[ResourceHandle.fromReadPipe(pipe.read)])
], 'Hello'.codeUnits);
pipe.write.add('Hello over pipe!'.codeUnits);
await pipe.write.flush();
await pipe.write.close();

Constructors

factory Pipe.createSync()

Synchronously creates an anonymous pipe.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final pipe = Pipe.createSync();
  pipe.write.add(utf8.encode('through the pipe'));
  await pipe.write.close();
  print(await pipe.read.transform(utf8.decoder).join());
}
Output from the Raya VM
through the pipe

Static

createstaticmethod
static Future<Pipe> create()
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final pipe = await Pipe.create();
  pipe.write.writeln('line one');
  pipe.write.writeln('line two');
  await pipe.write.close();
  print(await pipe.read.transform(utf8.decoder).transform(const LineSplitter()).toList());
}
Output from the Raya VM
[line one, line two]

Properties

readgetter
ReadPipe get read

The read end of the Pipe.

writegetter
WritePipe get write

The write end of the Pipe.

final class FileSystemEntityType

The type of an entity on the file system, such as a file, directory, or link.

These constants are used by the FileSystemEntity class to indicate the object's type.

Static

fileconstant
static const file = const FileSystemEntityType._internal(0)
directoryconstant
static const directory = const FileSystemEntityType._internal(1)
static const unixDomainSock = const FileSystemEntityType._internal(3)
pipeconstant
static const pipe = const FileSystemEntityType._internal(4)
notFoundconstant
static const notFound = const FileSystemEntityType._internal(5)
NOT_FOUNDconstantdeprecated
static const NOT_FOUND = notFound

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  for (final t in [FileSystemEntityType.file, FileSystemEntityType.directory, FileSystemEntityType.link, FileSystemEntityType.notFound]) {
    print(t);
  }
}
Output
file
directory
link
notFound
interface class FileStat

The result of calling the POSIX stat function on a file system object.

This is an immutable object, representing the snapshotted values returned by the stat call.

Static

statSyncstaticmethod
static FileStat statSync(String path)

Calls the operating system's stat function (or equivalent) on path.

If path is a symbolic link then it is resolved and results for the resulting file are returned.

Returns a FileStat object containing the data returned by stat. If the call fails, returns a FileStat object with FileStat.type set to FileSystemEntityType.notFound and the other fields invalid.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt')..writeAsStringSync('12345');
  final s = FileStat.statSync(f.path);
  print('type: ${s.type}, size: ${s.size}');
  print('missing: ${FileStat.statSync('${tmp.path}/nope').type}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
type: file, size: 5
missing: notFound
statstaticmethod
static Future<FileStat> stat(String path)

Asynchronously calls the operating system's stat function (or equivalent) on path.

If path is a symbolic link then it is resolved and results for the resulting file are returned.

Returns a Future which completes with the same results as statSync.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final s = await FileStat.stat(tmp.path);
  print('temp dir type: ${s.type}');
  print('modified is a DateTime: ${s.modified is DateTime}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
temp dir type: directory
modified is a DateTime: true

Properties

changedfield
final DateTime changed

The time of the last change to the data or metadata of the file system object.

On Windows platforms, this is instead the file creation time.

final DateTime modified

The time of the last change to the data of the file system object.

final DateTime accessed

The time of the last access to the data of the file system object.

On Windows platforms, this may have 1 day granularity, and be out of date by an hour.

typefield
final FileSystemEntityType type

The type of the underlying file system object.

FileSystemEntityType.notFound if stat or statSync failed.

modefield
final int mode

The mode of the file system object.

Permissions are encoded in the lower 16 bits of this number, and can be decoded using the modeString getter.

sizefield
final int size

The size of the file system object.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt')..writeAsStringSync('abc');
  final lines = f.statSync().toString().split('\n');
  // The first line names the type; the rest list times and mode.
  print(lines.first);
  print('lines: ${lines.length}, mentions mode: ${lines.any((l) => l.trim().startsWith('mode'))}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
FileStat: type file
lines: 6, mentions mode: true
String modeString()

The mode value as a human-readable string.

The string is in the format "rwxrwxrwx", reflecting the user, group, and world permissions to read, write, and execute the file system object, with "-" replacing the letter for missing permissions. Extra permission bits may be represented by prepending "(suid)", "(guid)", and/or "(sticky)" to the mode string.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/run.sh')..writeAsStringSync('echo hi');
  Process.runSync('chmod', ['750', f.path]);
  print('mode: ${f.statSync().modeString()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
mode: rwxr-x---
abstract class FileSystemEntity

The common superclass of File, Directory, and Link.

FileSystemEntity objects are returned from directory listing operations. To determine whether a FileSystemEntity is a File, a Directory, or a Link perform a type check:

if (entity is File) (entity as File).readAsStringSync();

You can also use the type or typeSync methods to determine the type of a file system object.

Most methods in this class exist both in synchronous and asynchronous versions, for example, exists and existsSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.

Here's the exists method in action:

var isThere = await entity.exists();
print(isThere ? 'exists' : 'nonexistent');

Static

identicalstaticmethod
static Future<bool> identical(String path1, String path2)

Checks whether two paths refer to the same object in the file system.

Returns a Future<bool> that completes with the result.

Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.

Completes the returned Future with an error if one of the paths points to an object that does not exist.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt')..writeAsStringSync('a');
  Link('${tmp.path}/ln').createSync(f.path);
  File('${tmp.path}/b.txt').writeAsStringSync('a');
  print('a vs ./a:   ${await FileSystemEntity.identical(f.path, '${tmp.path}/./a.txt')}');
  print('a vs link:  ${await FileSystemEntity.identical(f.path, '${tmp.path}/ln')}');
  print('a vs copy:  ${await FileSystemEntity.identical(f.path, '${tmp.path}/b.txt')}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
a vs ./a:   true
a vs link:  false
a vs copy:  false
identicalSyncstaticmethod
static bool identicalSync(String path1, String path2)

Synchronously checks whether two paths refer to the same object in the file system.

Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.

Throws an error if one of the paths points to an object that does not exist.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  Directory('${tmp.path}/x/y').createSync(recursive: true);
  print('x/y/.. is x: ${FileSystemEntity.identicalSync('${tmp.path}/x/y/..', '${tmp.path}/x')}');
  print('x is x/y:    ${FileSystemEntity.identicalSync('${tmp.path}/x', '${tmp.path}/x/y')}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
x/y/.. is x: true
x is x/y:    false
isWatchSupportedstaticgetter
static bool get isWatchSupported

Test if watch is supported on the current system.

OS X 10.6 and below is not supported.

typestaticmethod
static Future<FileSystemEntityType> type(String path, {bool followLinks = true})

Finds the type of file system object that a path points to.

Returns a Future<FileSystemEntityType> that completes with the same results as typeSync.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  File('${tmp.path}/f').writeAsStringSync('');
  Link('${tmp.path}/l').createSync('${tmp.path}/f');
  for (final n in ['f', 'l', 'missing']) {
    print('$n: ${await FileSystemEntity.type('${tmp.path}/$n')}');
  }
  print('l, links followed off: ${await FileSystemEntity.type('${tmp.path}/l', followLinks: false)}');
  print('tmp: ${await FileSystemEntity.type(tmp.path)}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
f: file
l: file
missing: notFound
l, links followed off: link
tmp: directory
typeSyncstaticmethod
static FileSystemEntityType typeSync(String path, {bool followLinks = true})

Synchronously finds the type of file system object that a path points to.

Returns FileSystemEntityType.notFound if path does not point to a file system object or if any other error occurs in looking up the path.

If path points to a link and followLinks is true then the result will be for the file system object that the link points to. If that object does not exist then the result will be FileSystemEntityType.notFound. If path points to a link and followLinks is false then the result will be FileSystemEntityType.link.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  File('${tmp.path}/data.csv').writeAsStringSync('1,2');
  Directory('${tmp.path}/out').createSync();
  for (final n in ['data.csv', 'out', 'nope']) {
    final t = FileSystemEntity.typeSync('${tmp.path}/$n');
    final label = switch (t) {
      FileSystemEntityType.file => 'a file',
      FileSystemEntityType.directory => 'a directory',
      FileSystemEntityType.notFound => 'not there',
      _ => 'something else',
    };
    print('$n is $label');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
data.csv is a file
out is a directory
nope is not there
isFilestaticmethod
static Future<bool> isFile(String path)

Whether path refers to a file.

Checks whether type(path) returns FileSystemEntityType.file.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/f')..writeAsStringSync('');
  Link('${tmp.path}/l').createSync(f.path);
  print('f:   ${await FileSystemEntity.isFile(f.path)}');
  print('l (link to a file, followed): ${await FileSystemEntity.isFile('${tmp.path}/l')}');
  print('tmp: ${await FileSystemEntity.isFile(tmp.path)}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
f:   true
l (link to a file, followed): true
tmp: false
isDirectorystaticmethod
static Future<bool> isDirectory(String path)

Whether path refers to a directory.

Checks whether type(path) returns FileSystemEntityType.directory.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  File('${tmp.path}/f').writeAsStringSync('');
  print('tmp is a directory: ${await FileSystemEntity.isDirectory(tmp.path)}');
  print('f is a directory:   ${await FileSystemEntity.isDirectory('${tmp.path}/f')}');
  print('missing:            ${await FileSystemEntity.isDirectory('${tmp.path}/none')}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
tmp is a directory: true
f is a directory:   false
missing:            false
isLinkSyncstaticmethod
static bool isLinkSync(String path)

Synchronously checks whether path refers to a link.

Checks whether typeSync(path, followLinks: false) returns FileSystemEntityType.link.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  Link('${tmp.path}/dangling').createSync('${tmp.path}/nothing-here');
  print('dangling link is a link: ${FileSystemEntity.isLinkSync('${tmp.path}/dangling')}');
  print('its target exists:       ${File('${tmp.path}/dangling').existsSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
dangling link is a link: true
its target exists:       false
isFileSyncstaticmethod
static bool isFileSync(String path)

Synchronously checks whether path refers to a file.

Checks whether typeSync(path) returns FileSystemEntityType.file.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  File('${tmp.path}/a.txt').writeAsStringSync('a');
  Directory('${tmp.path}/b').createSync();
  for (final n in ['a.txt', 'b']) {
    print('$n isFile: ${FileSystemEntity.isFileSync('${tmp.path}/$n')}');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
a.txt isFile: true
b isFile: false
isDirectorySyncstaticmethod
static bool isDirectorySync(String path)

Synchronously checks whether path refers to a directory.

Checks whether typeSync(path) returns FileSystemEntityType.directory.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  Directory('${tmp.path}/real').createSync();
  Link('${tmp.path}/alias').createSync('${tmp.path}/real');
  print('real:  ${FileSystemEntity.isDirectorySync('${tmp.path}/real')}');
  print('alias (link followed): ${FileSystemEntity.isDirectorySync('${tmp.path}/alias')}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
real:  true
alias (link followed): true
parentOfstaticmethod
static String parentOf(String path)

The parent path of a path.

Finds the final path component of a path, using the platform's path separator to split the path, and returns the prefix up to that part.

Will not remove the root component of a Windows path, like "C:\\" or "\\\\server_name\\". Includes a trailing path separator in the last part of path, and leaves no trailing path separator.

Example
import 'raya:io';

void main() {
  for (final p in ['/usr/local/bin', '/usr/local/bin/', 'docs/readme.md', 'readme.md', '/']) {
    print('parentOf("$p") = "${FileSystemEntity.parentOf(p)}"');
  }
}
Output from the Raya VM
parentOf("/usr/local/bin") = "/usr/local"
parentOf("/usr/local/bin/") = "/usr/local"
parentOf("docs/readme.md") = "docs"
parentOf("readme.md") = "."
parentOf("/") = "/"

Properties

pathgetter
String get path
urigetter
Uri get uri

A Uri representing the file system entity's location.

The returned URI's scheme is always "file" if the entity's path is absolute, otherwise the scheme will be empty and the URI relative.

bool get isAbsolute

Whether this object's path is absolute.

An absolute path is independent of the current working directory (Directory.current). A non-absolute path must be interpreted relative to the current working directory.

On Windows, a path is absolute if it starts with \\ (two backslashes or representing a UNC path) or with a drive letter between a and z (upper or lower case) followed by :\ or :/. This makes, for example, \file.ext a non-absolute path because it depends on the current drive letter.

On non-Windows, a path is absolute if it starts with /.

If the path is not absolute, use absolute to get an entity with an absolute path referencing the same object in the file system, if possible.

absolutegetter
FileSystemEntity get absolute

A FileSystemEntity whose path is the absolute path of path.

The type of the returned instance is the same as the type of this entity.

A file system entity with an already absolute path (as reported by isAbsolute) is returned directly. For a non-absolute path, the returned entity is absolute (isAbsolute) if possible, but still refers to the same file system object.

parentgetter
Directory get parent

The parent directory of this entity.

Methods

existsmethod
Future<bool> exists()

Checks whether the file system entity with this path exists.

Returns a Future<bool> that completes with the result.

Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling exists on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the type static method.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/maybe.txt');
  print('before: ${await file.exists()}');
  await file.writeAsString('now');
  print('after:  ${await file.exists()}');
  // A File object does not exist as a Directory.
  print('as dir: ${await Directory(file.path).exists()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
before: false
after:  true
as dir: false
bool existsSync()

Synchronously checks whether the file system entity with this path exists.

Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling existsSync on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the typeSync static method.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final cfg = File('${tmp.path}/settings.json');
  if (!cfg.existsSync()) {
    cfg.writeAsStringSync('{"theme": "dark"}');
    print('created default settings');
  }
  print('exists now: ${cfg.existsSync()}');
  print('contents:   ${cfg.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
created default settings
exists now: true
contents:   {"theme": "dark"}
renamemethod
Future<FileSystemEntity> rename(String newPath)

Renames this file system entity.

Returns a Future<FileSystemEntity> that completes with a FileSystemEntity instance for the renamed file system entity.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final FileSystemEntity e = File('${tmp.path}/in.txt')..writeAsStringSync('payload');
  final moved = await e.rename('${tmp.path}/out.txt');
  print('moved type: ${moved.runtimeType == e.runtimeType}');
  print('name:       ${moved.path.split('/').last}');
  print('old gone:   ${!await e.exists()}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
moved type: true
name:       out.txt
old gone:   true
FileSystemEntity renameSync(String newPath)

Synchronously renames this file system entity.

Returns a FileSystemEntity instance for the renamed entity.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final entities = <FileSystemEntity>[
    File('${tmp.path}/f')..writeAsStringSync('f'),
    Directory('${tmp.path}/d')..createSync(),
  ];
  for (final e in entities) {
    final r = e.renameSync('${e.path}_renamed');
    print('${e.path.split('/').last} -> ${r.path.split('/').last}');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
f -> f_renamed
d -> d_renamed
String resolveSymbolicLinksSync()

Resolves the path of a file system object relative to the current working directory.

Resolves all symbolic links on the path and resolves all .. and . path segments.

resolveSymbolicLinksSync uses the operating system's native file system API to resolve the path, using the realpath function on linux and OS X, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinksSync throws a FileSystemException.

On Windows the .. segments are resolved before resolving the symbolic link, and on other platforms the symbolic links are resolved to their target before applying a .. that follows.

To ensure the same behavior on all platforms resolve .. segments before calling resolveSymbolicLinksSync. One way of doing this is with the Uri class:

var path = Uri.parse('.').resolveUri(Uri.file(input)).toFilePath();
if (path == '') path = '.';
var resolved = File(path).resolveSymbolicLinksSync();
print(resolved);

Since Uri.resolve removes .. segments. This will result in the Windows behavior.

On Windows, a symbolic link is created as either a file link or a directory link. Attempting to resolve such a symbolic link requires the link type to match the type of the file system object that it points to, otherwise it throws a PathAccessException.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final root = tmp.resolveSymbolicLinksSync();
  try {
    File('$root/missing').resolveSymbolicLinksSync();
  } on FileSystemException {
    print('missing path: FileSystemException');
  }
  Directory('$root/a/b').createSync(recursive: true);
  final r = Directory('$root/a/./b/../b').resolveSymbolicLinksSync();
  print('a/./b/../b -> ${r.substring(root.length + 1)}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
missing path: FileSystemException
a/./b/../b -> a/b
statmethod
Future<FileStat> stat()

Calls the operating system's stat function on path.

Identical to FileStat.stat(this.path).

Returns a Future<FileStat> object containing the data returned by stat.

If path is a symbolic link then it is resolved and results for the resulting file are returned.

If the call fails, completes the future with a FileStat object with .type set to FileSystemEntityType.notFound and the other fields invalid.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/s.txt')..writeAsStringSync('12345');
  final s = await f.stat();
  print('type: ${s.type}');
  print('size: ${s.size}');
  final dirStat = await tmp.stat();
  print('tmp type: ${dirStat.type}');
  await tmp.delete(recursive: true);
}
Output from the Raya VM
type: file
size: 5
tmp type: directory
statSyncmethod
FileStat statSync()

Synchronously calls the operating system's stat function on path.

Identical to FileStat.statSync(this.path).

Returns a FileStat object containing the data returned by stat.

If path is a symbolic link then it is resolved and results for the resulting file are returned.

If the call fails, returns a FileStat object with .type set to FileSystemEntityType.notFound and the other fields invalid.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final s = File('${tmp.path}/missing').statSync();
  print('missing type: ${s.type}');
  print('missing size: ${s.size}');
  final f = File('${tmp.path}/x')..writeAsStringSync('abc');
  f.setLastModifiedSync(DateTime.utc(2021, 5, 4));
  final fs = f.statSync();
  print('file: ${fs.type}, ${fs.size} bytes, modified ${fs.modified.toUtc().toIso8601String()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
missing type: notFound
missing size: -1
file: file, 3 bytes, modified 2021-05-04T00:00:00.000Z
deletemethod
Future<FileSystemEntity> delete({bool recursive = false})

Deletes this FileSystemEntity.

The exact details vary according to the FileSystemEntity:

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final items = <FileSystemEntity>[
    File('${tmp.path}/f.txt')..writeAsStringSync('f'),
    Directory('${tmp.path}/d')..createSync(),
  ];
  for (final e in items) {
    await e.delete();
    print('${e.path.split('/').last} deleted: ${!await e.exists()}');
  }
  await tmp.delete(recursive: true);
}
Output from the Raya VM
f.txt deleted: true
d deleted: true
void deleteSync({bool recursive = false})

Synchronously deletes this FileSystemEntity.

The exact details vary according to the FileSystemEntity:

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final target = File('${tmp.path}/t.txt')..writeAsStringSync('keep me');
  final link = Link('${tmp.path}/l')..createSync(target.path);
  link.deleteSync(); // removes the link, not the target
  print('link gone:   ${!link.existsSync()}');
  print('target kept: ${target.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
link gone:   true
target kept: keep me
watchmethod
Stream<FileSystemEvent> watch({int events = FileSystemEvent.all, bool recursive = false})

Start watching the FileSystemEntity for changes.

The implementation uses platform-dependent event-based APIs for receiving file-system notifications, thus behavior depends on the platform.

  • Windows: Uses ReadDirectoryChangesW. The implementation only supports watching directories. Recursive watching is supported.
  • Linux: Uses inotify. The implementation supports watching both files and directories. Recursive watching is not supported. Note: When watching files directly, delete events might not happen as expected.
  • OS X: Uses the File System Events API. The implementation supports watching both files and directories. Recursive watching is supported. This API has several limitations:
  • Changes that occurred shortly before the watch method was called may still appear in the Stream.
  • Changes that occur in a short period of time may arrive out-of-order.
  • Multiple changes made in a single directory may be coalesced into a single FileSystemEvent.

The system will start listening for events once the returned Stream is being listened to, not when the call to watch is issued.

The returned value is an endless broadcast Stream, that only stops when one of the following happens:

  • The Stream is canceled, e.g. by calling cancel on the StreamSubscription.
  • The FileSystemEntity being watched is deleted.
  • System Watcher exits unexpectedly. e.g. On Windows this happens when buffer that receive events from ReadDirectoryChangesW overflows.

Use events to specify what events to listen for. The constants in FileSystemEvent can be or'ed together to mix events. Default is FileSystemEvent.all.

A move event may be reported as separate delete and create events.

Example
import 'raya:io';

void main() {
  // watch() reports changes as a stream of FileSystemEvents. Event types are bit flags:
  print('create: ${FileSystemEvent.create}');
  print('modify: ${FileSystemEvent.modify}');
  print('delete: ${FileSystemEvent.delete}');
  print('move:   ${FileSystemEvent.move}');
  print('all:    ${FileSystemEvent.all}');
  print('watch only creates and deletes: mask ${FileSystemEvent.create | FileSystemEvent.delete}');
}
Output
create: 1
modify: 2
delete: 4
move:   8
all:    15
watch only creates and deletes: mask 5
sealed class FileSystemEvent

Base event class emitted by FileSystemEntity.watch.

Static

createconstant
static const int create = 1 << 0
modifyconstant
static const int modify = 1 << 1
deleteconstant
static const int delete = 1 << 2
moveconstant
static const int move = 1 << 3
allconstant
static const int all = create | modify | delete | move

Bitfield for FileSystemEntity.watch, for enabling all of create, modify, delete and move.

Properties

typefield
final int type

The type of event. See FileSystemEvent for a list of events.

pathfield
final String path

The path that triggered the event.

Depending on the platform and the FileSystemEntity, the path may be relative.

final bool isDirectory

Whether the event target is a directory.

The value will always be false for FileSystemDeleteEvent.

On Windows isDirectory is computed by checking the file system entity type after the event, which means it can be incorrect. It can be incorrectly false for a directory create, modify or move event if that directory was deleted soon after the event occurred. And, it can be incorrectly true for a newly created link to a directory.

final class FileSystemCreateEvent extends FileSystemEvent

File system event for newly created file system objects.

Constructors

FileSystemCreateEvent(String path, bool isDirectory)

Constructs a new FileSystemCreateEvent.

Example
import 'raya:io';

void main() {
  final e = FileSystemCreateEvent('logs/today.txt', false);
  print('type ${e.type == FileSystemEvent.create}, path ${e.path}, isDirectory ${e.isDirectory}');
}
Output
type true, path logs/today.txt, isDirectory false

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(FileSystemCreateEvent('build', true));
}
Output
FileSystemCreateEvent('build', isDirectory=true)
final class FileSystemModifyEvent extends FileSystemEvent

File system event for modifications of file system objects.

Constructors

FileSystemModifyEvent(String path, bool isDirectory, this.contentChanged)

Constructs a new FileSystemModifyEvent.

Example
import 'raya:io';

void main() {
  final e = FileSystemModifyEvent('notes.txt', false, true);
  print('contentChanged: ${e.contentChanged}, type is modify: ${e.type == FileSystemEvent.modify}');
}
Output
contentChanged: true, type is modify: true

Properties

final bool contentChanged

If the content was changed and not only the attributes, contentChanged is true.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(FileSystemModifyEvent('notes.txt', false, false));
}
Output
FileSystemModifyEvent('notes.txt', isDirectory=false, contentChanged=false)
final class FileSystemDeleteEvent extends FileSystemEvent

File system event for deletion of file system objects.

Constructors

FileSystemDeleteEvent(String path, bool isDirectory)

Constructs a new FileSystemDeleteEvent.

Example
import 'raya:io';

void main() {
  final e = FileSystemDeleteEvent('tmp/cache', true);
  print('deleted ${e.path}, directory: ${e.isDirectory}');
}
Output
deleted tmp/cache, directory: false

Properties

isDirectorygetterdeprecated
bool get isDirectory

Whether the file system object was a directory.

The value will always be false for FileSystemDeleteEvent.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(FileSystemDeleteEvent('old.log', false));
}
Output
FileSystemDeleteEvent('old.log')
final class FileSystemMoveEvent extends FileSystemEvent

File system event for moving of file system objects.

Constructors

FileSystemMoveEvent(String path, bool isDirectory, this.destination)

Constructs a new FileSystemMoveEvent.

Example
import 'raya:io';

void main() {
  final e = FileSystemMoveEvent('draft.md', false, 'final.md');
  print('moved ${e.path} -> ${e.destination}');
}
Output
moved draft.md -> final.md

Properties

final String? destination

The destination path of the file being moved.

The destination is null if the underlying implementation is unable to identify the destination of the moved file.

The source path is available as path.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(FileSystemMoveEvent('a.txt', false, 'b.txt'));
}
Output
FileSystemMoveEvent('a.txt', isDirectory=false, destination=b.txt)
class

IOSink

abstract interface class IOSink implements StreamSink<List<int>>, StringSink

A combined byte and text output.

An IOSink combines a StreamSink of bytes with a StringSink, and allows easy output of both bytes and text.

An IOSink is intended for writing bytes. Strings written through write or writeCharCode will be converted to bytes using encoding. Integer data added using add or addStream will be treated as byte data, and will be truncated to unsigned 8-bit values as by using int.toUnsigned. No guarantees are given for when such a conversion happens, since it depends on the implementation behind the sink.

Writing text (write) and adding bytes (add) may be interleaved freely.

While a stream is being added using addStream, any further attempts to add or write to the IOSink will fail until the addStream completes.

It is an error to add data to the IOSink after the sink is closed.

Constructors

IOSinkfactory
factory IOSink(StreamConsumer<List<int>> target, {Encoding encoding = utf8})

Create an IOSink that outputs to a target StreamConsumer of bytes.

Text written to StreamSink methods is encoded to bytes using encoding before being output on target.

Example
import 'raya:io';
import 'raya:async';
import 'raya:convert';

Future<void> main() async {
  final collected = StreamController<List<int>>();
  final sink = IOSink(collected.sink, encoding: latin1);
  sink.write('café');
  final bytes = collected.stream.expand((c) => c).toList();
  await sink.close();
  print('latin1 bytes: ${await bytes}');
}
Output
latin1 bytes: [99, 97, 102, 233]

Properties

late Encoding encoding

The Encoding used when writing strings.

Depending on the underlying consumer, this property might be mutable.

donegetter
Future get done

A future that will complete when the consumer closes, or when an error occurs.

This future is identical to the future returned by close.

Methods

addmethod
void add(List<int> data)

Adds byte data to the target consumer, ignoring encoding.

The encoding does not apply to this method, and the data list is passed directly to the target consumer as a stream event.

This method must not be called when a stream is currently being added using addStream.

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

The data list should not be modified after it has been passed to add because it is not defined whether the target consumer will receive the list in the original or modified state.

Individual values in data which are not in the range 0.. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.bin');
  final sink = f.openWrite();
  sink.add([1, 2, 3]);
  sink.add([4]);
  await sink.close();
  print('file bytes: ${f.readAsBytesSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
file bytes: [1, 2, 3, 4]
writemethod
void write(Object? object)

Converts object to a String by invoking Object.toString and adds the encoding of the result to the target consumer.

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt');
  final sink = f.openWrite();
  sink.write('n = ');
  sink.write(42);
  sink.write(', ok = ');
  sink.write(true);
  await sink.close();
  print(f.readAsStringSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
n = 42, ok = true
writeAllmethod
void writeAll(Iterable objects, [String separator = ""])

Iterates over the given objects and writes them in sequence.

If separator is provided, a write with the separator is performed between any two elements of objects.

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/row.csv');
  final sink = f.openWrite();
  sink.writeAll(['id', 'name', 'score'], ',');
  sink.write('\n');
  sink.writeAll([1, 'Ada', 99.5], ',');
  await sink.close();
  print(f.readAsStringSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
id,name,score
1,Ada,99.5
writelnmethod
void writeln([Object? object = ""])

Converts object to a String by invoking Object.toString and writes the result to this, followed by a newline.

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt');
  final sink = f.openWrite()
    ..writeln('first')
    ..writeln()
    ..writeln('third');
  await sink.close();
  print(f.readAsLinesSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
[first, , third]
void writeCharCode(int charCode)

Writes the character of charCode.

This method is equivalent to write(String.fromCharCode(charCode)).

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt');
  final sink = f.openWrite();
  for (final c in [0x52, 0x61, 0x79, 0x61, 0x2713]) {
    sink.writeCharCode(c);
  }
  await sink.close();
  print('${f.readAsStringSync()} (${f.lengthSync()} bytes in UTF-8)');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
Raya✓ (7 bytes in UTF-8)
addErrormethod
void addError(error, [StackTrace? stackTrace])

Passes the error to the target consumer as an error event.

This method must not be called when a stream is currently being added using addStream.

This operation is non-blocking. See flush or done for how to get any errors generated by this call.

Example
import 'raya:io';
import 'raya:async';

Future<void> main() async {
  final target = StreamController<List<int>>();
  final sink = IOSink(target.sink);
  final errors = target.stream.handleError((e) => print('consumer got error: $e')).drain<void>();
  sink.add([1]);
  sink.addError(StateError('upstream failed'));
  await sink.close();
  await errors;
}
Output
consumer got error: Bad state: upstream failed
addStreammethod
Future addStream(Stream<List<int>> stream)

Adds all elements of the given stream.

Returns a Future that completes when all elements of the given stream have been added.

If the stream contains an error, the addStream ends at the error, and the returned future completes with that error.

This method must not be called when a stream is currently being added using this method.

Individual values in the lists emitted by stream which are not in the range 0.. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt');
  final sink = f.openWrite();
  await sink.addStream(Stream.fromIterable(['alpha ', 'beta ', 'gamma']).transform(utf8.encoder));
  sink.write('!');
  await sink.close();
  print(f.readAsStringSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
alpha beta gamma!
flushmethod
Future flush()

Returns a Future that completes once all buffered data is accepted by the underlying StreamConsumer.

This method must not be called while an addStream is incomplete.

NOTE: This is not necessarily the same as the data being flushed by the operating system.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final f = File('${tmp.path}/a.txt');
  final sink = f.openWrite();
  sink.write('partial');
  await sink.flush();
  print('on disk after flush: ${f.readAsStringSync()}');
  sink.write(' and more');
  await sink.close();
  print('after close: ${f.readAsStringSync()}');
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
on disk after flush: partial
after close: partial and more
closemethod
Future close()

Close the target consumer.

NOTE: Writes to the IOSink may be buffered, and may not be flushed by a call to close. To flush all buffered writes, call flush before calling close.

Example
import 'raya:io';

Future<void> main() async {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final sink = File('${tmp.path}/a.txt').openWrite();
  sink.write('done');
  await sink.close();
  try {
    sink.write('late');
  } on StateError catch (e) {
    print('write after close: ${e.message}');
  }
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
write after close: StreamSink is closed
abstract base class IOOverrides

Facilities for overriding various APIs of raya:io with mock implementations.

This abstract base class should be extended with overrides for the operations needed to construct mocks. The implementations in this base class default to the actual raya:io implementation. For example:

class MyDirectory implements Directory {
  ...
  // An implementation of the Directory interface
  ...
}

void main() {
  IOOverrides.runZoned(() {
    ...
    // Operations will use MyDirectory instead of raya:io's Directory
    // implementation whenever Directory is used.
    ...
  }, createDirectory: (String path) => new MyDirectory(path));
}

Static

currentstaticgetter
static IOOverrides? get current
globalstaticsetter
static set global(IOOverrides? overrides)

The IOOverrides to use in the root Zone.

These are the IOOverrides that will be used in the root Zone, and in Zone's that do not set IOOverrides and whose ancestors up to the root Zone also do not set IOOverrides.

Example
import 'raya:io';

final class FixedTemp extends IOOverrides {
  @override
  Directory getSystemTempDirectory() => Directory('/sandbox/tmp');
}

void main() {
  IOOverrides.global = FixedTemp(); // applies everywhere, not just in a zone
  print('systemTemp: ${Directory.systemTemp.path}');
  IOOverrides.global = null;
  print('restored: ${Directory.systemTemp.path != '/sandbox/tmp'}');
}
Output from the Raya VM
systemTemp: /sandbox/tmp
restored: true
runZonedstaticmethod
static R runZoned<R>(R body(), {Directory Function(String)? createDirectory, Directory Function()? getCurrentDirectory, void Function(String)? setCurrentDirectory, Directory Function()? getSystemTempDirectory, File Function(String)? createFile, Future<FileStat> Function(String)? stat, FileStat Function(String)? statSync, Future<bool> Function(String, String)? fseIdentical, bool Function(String, String)? fseIdenticalSync, Future<FileSystemEntityType> Function(String, bool)? fseGetType, FileSystemEntityType Function(String, bool)? fseGetTypeSync, Stream<FileSystemEvent> Function(String, int, bool)? fsWatch, bool Function()? fsWatchIsSupported, Link Function(String)? createLink, Future<Socket> Function(dynamic, int, {dynamic sourceAddress, int sourcePort, Duration? timeout})? socketConnect, Future<ConnectionTask<Socket>> Function(dynamic, int, {dynamic sourceAddress, int sourcePort})? socketStartConnect, Future<ServerSocket> Function(dynamic, int, {int backlog, bool v6Only, bool shared})? serverSocketBind, Stdin Function()? stdin, Stdout Function()? stdout, Stdout Function()? stderr, @Since("3.10") Never Function(int)? exit})

Runs body in a fresh Zone using the provided overrides.

See the documentation on the corresponding methods of IOOverrides for information about what the optional arguments do.

Example
import 'raya:io';

void main() {
  final created = <String>[];
  // Build the replacement outside the zone: calling File() inside createFile would recurse.
  final virtual = File('/virtual/file');
  IOOverrides.runZoned(() {
    File('report.txt');
    File('data/raw.csv');
    print('current dir inside: ${Directory.current.path}');
  }, createFile: (path) {
    created.add(path);
    return virtual;
  }, getCurrentDirectory: () => Directory('/virtual'));
  print('files requested through the override: $created');
}
Output
current dir inside: /virtual
files requested through the override: [report.txt, data/raw.csv]
runWithIOOverridesstaticmethod
static R runWithIOOverrides<R>(R body(), IOOverrides overrides)

Runs body in a fresh Zone using the overrides found in overrides.

Note that overrides should be an instance of a class that extends IOOverrides.

Example
import 'raya:io';

final class ReadOnlyFiles extends IOOverrides {
  final opened = <String>[];
  @override
  File createFile(String path) {
    opened.add(path);
    return super.createFile(path);
  }
}

void main() {
  final o = ReadOnlyFiles();
  IOOverrides.runWithIOOverrides(() {
    File('a.txt');
    File('b.txt');
  }, o);
  print('File objects made in the zone: ${o.opened}');
}
Output
File objects made in the zone: [a.txt, b.txt]

Properties

stdingetter
Stdin get stdin

The standard input stream of data read by this program.

When this override is installed, this getter overrides the behavior of the top-level stdin getter.

stdoutgetter
Stdout get stdout

The standard output stream of data written by this program.

When this override is installed, this getter overrides the behavior of the top-level stdout getter.

stderrgetter
Stdout get stderr

The standard output stream of errors written by this program.

When this override is installed, this getter overrides the behavior of the top-level stderr getter.

Methods

Directory createDirectory(String path)

Creates a new Directory object for the given path.

When this override is installed, this function overrides the behavior of new Directory and new Directory.fromUri.

Example
import 'raya:io';

final class Chroot extends IOOverrides {
  @override
  Directory createDirectory(String path) => super.createDirectory('/jail${path.startsWith('/') ? '' : '/'}$path');
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print(Directory('/etc').path);
    print(Directory('home/ada').path);
  }, Chroot());
}
Output
/jail/etc
/jail/home/ada
Directory getCurrentDirectory()

Returns the current working directory.

When this override is installed, this function overrides the behavior of the static getter Directory.current

Example
import 'raya:io';

final class InProject extends IOOverrides {
  @override
  Directory getCurrentDirectory() => Directory('/work/project');
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print('Directory.current: ${Directory.current.path}');
  }, InProject());
}
Output
Directory.current: /work/project
void setCurrentDirectory(String path)

Sets the current working directory to be path.

When this override is installed, this function overrides the behavior of the setter Directory.current.

Example
import 'raya:io';

final class TrackCd extends IOOverrides {
  String cwd = '/';
  @override
  void setCurrentDirectory(String path) => cwd = path;
  @override
  Directory getCurrentDirectory() => Directory(cwd);
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    Directory.current = '/tmp/build';
    print('after cd: ${Directory.current.path}');
  }, TrackCd());
}
Output
after cd: /tmp/build
Directory getSystemTempDirectory()

Returns the system temporary directory.

When this override is installed, this function overrides the behavior of Directory.systemTemp.

Example
import 'raya:io';

void main() {
  IOOverrides.runZoned(() {
    print('systemTemp: ${Directory.systemTemp.path}');
  }, getSystemTempDirectory: () => Directory('/ramdisk/tmp'));
}
Output
systemTemp: /ramdisk/tmp
File createFile(String path)

Creates a new File object for the given path.

When this override is installed, this function overrides the behavior of new File and new File.fromUri.

Example
import 'raya:io';

final class Prefixed extends IOOverrides {
  @override
  File createFile(String path) => super.createFile('out/$path');
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print(File('log.txt').path);
  }, Prefixed());
  print('outside: ${File('log.txt').path}');
}
Output
out/log.txt
outside: log.txt
statmethod
Future<FileStat> stat(String path)

Asynchronously returns FileStat information for path.

When this override is installed, this function overrides the behavior of FileStat.stat.

Example
import 'raya:io';

final class AllMissing extends IOOverrides {
  @override
  Future<FileStat> stat(String path) => super.stat('/definitely/not/here');
}

Future<void> main() async {
  await IOOverrides.runWithIOOverrides(() async {
    final s = await FileStat.stat('/');
    print('stat("/") inside the override: ${s.type}');
  }, AllMissing());
}
Output from the Raya VM
stat("/") inside the override: notFound
statSyncmethod
FileStat statSync(String path)

Returns FileStat information for path.

When this override is installed, this function overrides the behavior of FileStat.statSync.

Example
import 'raya:io';

final class Logged extends IOOverrides {
  final paths = <String>[];
  @override
  FileStat statSync(String path) {
    paths.add(path);
    return super.statSync(path);
  }
}

void main() {
  final o = Logged();
  IOOverrides.runWithIOOverrides(() => FileStat.statSync('/'), o);
  print('statSync calls: ${o.paths}');
}
Output from the Raya VM
statSync calls: [/]
Future<bool> fseIdentical(String path1, String path2)

Asynchronously returns true if path1 and path2 are paths to the same file system object.

When this override is installed, this function overrides the behavior of FileSystemEntity.identical.

Example
import 'raya:io';

final class SameEverything extends IOOverrides {
  @override
  Future<bool> fseIdentical(String a, String b) async => true;
}

Future<void> main() async {
  await IOOverrides.runWithIOOverrides(() async {
    print('identical(a, b): ${await FileSystemEntity.identical('a', 'b')}');
  }, SameEverything());
}
Output
identical(a, b): true
bool fseIdenticalSync(String path1, String path2)

Returns true if path1 and path2 are paths to the same file system object.

When this override is installed, this function overrides the behavior of FileSystemEntity.identicalSync.

Example
import 'raya:io';

final class CaseInsensitive extends IOOverrides {
  @override
  bool fseIdenticalSync(String a, String b) => a.toLowerCase() == b.toLowerCase();
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print('README vs readme: ${FileSystemEntity.identicalSync('README', 'readme')}');
  }, CaseInsensitive());
}
Output
README vs readme: true
Future<FileSystemEntityType> fseGetType(String path, bool followLinks)

Asynchronously returns the FileSystemEntityType for path.

When this override is installed, this function overrides the behavior of FileSystemEntity.type.

Example
import 'raya:io';

final class VirtualFs extends IOOverrides {
  @override
  Future<FileSystemEntityType> fseGetType(String path, bool followLinks) async =>
      path.endsWith('/') ? FileSystemEntityType.directory : FileSystemEntityType.file;
}

Future<void> main() async {
  await IOOverrides.runWithIOOverrides(() async {
    print('docs/: ${await FileSystemEntity.type('docs/')}');
    print('a.txt: ${await FileSystemEntity.type('a.txt')}');
  }, VirtualFs());
}
Output
docs/: directory
a.txt: file
FileSystemEntityType fseGetTypeSync(String path, bool followLinks)

Returns the FileSystemEntityType for path.

When this override is installed, this function overrides the behavior of FileSystemEntity.typeSync.

Example
import 'raya:io';

final class OnlyDirs extends IOOverrides {
  @override
  FileSystemEntityType fseGetTypeSync(String path, bool followLinks) => FileSystemEntityType.directory;
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print('anything is a directory: ${FileSystemEntity.isDirectorySync('x.txt')}');
  }, OnlyDirs());
}
Output
anything is a directory: true
fsWatchmethod
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive)

Returns a Stream of FileSystemEvents.

When this override is installed, this function overrides the behavior of FileSystemEntity.watch.

Example
import 'raya:io';

final class FakeWatch extends IOOverrides {
  @override
  Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) =>
      Stream.fromIterable([FileSystemCreateEvent('$path/new.txt', false)]);
}

Future<void> main() async {
  await IOOverrides.runWithIOOverrides(() async {
    await for (final e in Directory('/data').watch()) {
      print('event: $e');
    }
  }, FakeWatch());
}
Output from the Raya VM
event: FileSystemCreateEvent('/data/new.txt', isDirectory=false)
bool fsWatchIsSupported()

Returns true when FileSystemEntity.watch is supported.

When this override is installed, this function overrides the behavior of FileSystemEntity.isWatchSupported.

Example
import 'raya:io';

final class NoWatch extends IOOverrides {
  @override
  bool fsWatchIsSupported() => false;
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    print('isWatchSupported in the zone: ${FileSystemEntity.isWatchSupported}');
  }, NoWatch());
}
Output
isWatchSupported in the zone: false
Future<Socket> socketConnect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout})

Asynchronously returns a Socket connected to the given host and port.

When this override is installed, this function overrides the behavior of Socket.connect(...).

Example
import 'raya:io';

final class Redirect extends IOOverrides {
  final int port;
  Redirect(this.port);
  @override
  Future<Socket> socketConnect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout}) =>
      super.socketConnect(InternetAddress.loopbackIPv4, this.port);
}

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s..write('hello from the local server')..close()..drain<void>());
  await IOOverrides.runWithIOOverrides(() async {
    final s = await Socket.connect('example.invalid', 80).timeout(t); // goes to localhost instead
    print(String.fromCharCodes(await s.expand((c) => c).toList().timeout(t)));
    s.destroy();
  }, Redirect(server.port));
  await server.close();
}
Output from the Raya VM
hello from the local server
Future<ConnectionTask<Socket>> socketStartConnect(host, int port, {sourceAddress, int sourcePort = 0})

Asynchronously returns a ConnectionTask that connects to the given host and port when successful.

When this override is installed, this function overrides the behavior of Socket.startConnect(...).

Example
import 'raya:io';

final class Count extends IOOverrides {
  var starts = 0;
  @override
  Future<ConnectionTask<Socket>> socketStartConnect(host, int port, {sourceAddress, int sourcePort = 0}) {
    starts++;
    return super.socketStartConnect(host, port);
  }
}

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final o = Count();
  await IOOverrides.runWithIOOverrides(() async {
    final task = await Socket.startConnect(InternetAddress.loopbackIPv4, server.port);
    (await task.socket.timeout(const Duration(seconds: 2))).destroy();
  }, o);
  print('startConnect calls seen: ${o.starts}');
  await server.close();
}
Output from the Raya VM
startConnect calls seen: 1
Future<ServerSocket> serverSocketBind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false})

Asynchronously returns a ServerSocket that connects to the given address and port when successful.

When this override is installed, this function overrides the behavior of ServerSocket.bind(...).

Example
import 'raya:io';

final class LoopbackOnly extends IOOverrides {
  @override
  Future<ServerSocket> serverSocketBind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false}) =>
      super.serverSocketBind(InternetAddress.loopbackIPv4, port);
}

Future<void> main() async {
  await IOOverrides.runWithIOOverrides(() async {
    final s = await ServerSocket.bind(InternetAddress.anyIPv4, 0);
    print('asked for any address, bound to: ${s.address.address}');
    await s.close();
  }, LoopbackOnly());
}
Output from the Raya VM
asked for any address, bound to: 127.0.0.1
exitmethod
Never exit(int code)

Exit the Raya VM process immediately with the given exit code.

When this override is installed, this function overrides the behavior of exit(...).

Example
import 'raya:io';

final class NoExit extends IOOverrides {
  @override
  Never exit(int code) => throw StateError('exit($code) blocked in tests');
}

void main() {
  IOOverrides.runWithIOOverrides(() {
    try {
      exit(1);
    } on StateError catch (e) {
      print(e.message);
    }
  }, NoExit());
}
Output
exit(1) blocked in tests
abstract final class Platform

Information about the environment in which the current program is running.

Platform provides information such as the operating system, the hostname of the computer, the value of environment variables, the path to the running program, and other global properties of the program being run.

Get the URI of the current Raya script

Use the script getter to get the URI to the currently running Raya script.

import 'raya:io' show Platform;

void main() {
  // Get the URI of the script being run.
  var uri = Platform.script;
  // Convert the URI to a path.
  var path = uri.toFilePath();
}
Get the value of an environment variable

The environment getter returns a the names and values of environment variables in a Map that contains key-value pairs of strings. The Map is unmodifiable. This sample shows how to get the value of the PATH environment variable.

import 'raya:io' show Platform;

void main() {
  Map<String, String> envVars = Platform.environment;
  print(envVars['PATH']);
}
Determine the OS

You can get the name of the operating system as a string with the operatingSystem getter. You can also use one of the static boolean getters: isMacOS, isLinux, isWindows, etc.

import 'raya:io' show Platform;

void main() {
  // Get the operating system as a string.
  String os = Platform.operatingSystem;
  // Or, use a predicate getter.
  if (Platform.isMacOS) {
    print('is a Mac');
  } else {
    print('is not a Mac');
  }
}

Static

static final numberOfProcessors

The number of individual execution units of the machine.

pathSeparatorstaticfield
static final pathSeparator

The path separator used by the operating system to separate components in file paths.

operatingSystemstaticfield
static final operatingSystem

A string representing the operating system or platform.

Possible values include:

  • "android"
  • "fuchsia"
  • "ios"
  • "linux"
  • "macos"
  • "windows"

Note that this list may change over time so platform-specific logic should be guarded by the appropriate Boolean getter e.g. isMacOS.

static final operatingSystemVersion

A string representing the version of the operating system or platform.

The format of this string will vary by operating system, platform and version and is not suitable for parsing. For example: "Linux 5.11.0-1018-gcp #20~20.04.2-Ubuntu SMP Fri Sep 3 01:01:37 UTC 2021" "Version 14.5 (Build 18E182)" '"Windows 10 Pro" 10.0 (Build 19043)'

localHostnamestaticfield
static final localHostname

The local hostname for the system.

For example: "mycomputer.corp.example.com" "mycomputer"

Uses the platform 0 implementation.

versionstaticfield
static final version

The version of the current Raya runtime.

The value is a semantic versioning string representing the version of the current Raya runtime, possibly followed by whitespace and other version and build details.

localeNamestaticgetter
static String get localeName

Get the name of the current locale.

The result usually consists of

  • A language (e.g. "en"), or
  • A language and country code (e.g. "en_US", "de_AT"), or
  • A language, country code and character set (e.g. "en_US.UTF-8").

On macOS and iOS, the locale is taken from CFLocaleGetIdentifier.

On Linux and Fuchsia, the locale is taken from the "LANG" environment variable, which may be set to any value. For example:

LANG=kitten raya myfile.ray  # localeName is "kitten"

On Android, the value will not change while the application is running, even if the user adjusts their language settings.

See https://en.wikipedia.org/wiki/Locale_(computer_software)

isLinuxstaticfield
static final bool isLinux

Whether the operating system is a version of Linux.

This value is false if the operating system is a specialized version of Linux that identifies itself by a different name, for example Android (see isAndroid).

isMacOSstaticfield
static final bool isMacOS

Whether the operating system is a version of macOS.

isWindowsstaticfield
static bool isWindows

Whether the operating system is a version of Microsoft Windows.

isAndroidstaticfield
static final bool isAndroid

Whether the operating system is a version of Android.

isIOSstaticfield
static final bool isIOS

Whether the operating system is a version of iOS.

isFuchsiastaticfield
static final bool isFuchsia

Whether the operating system is a version of Fuchsia.

environmentstaticgetter
static Map<String, String> get environment

The environment for this process as a map from string key to string value.

The map is unmodifiable, and its content is retrieved from the operating system on its first use.

Environment variables on Windows are case-insensitive, so on Windows the map is case-insensitive and will convert all keys to upper case. On other platforms, keys can be distinguished by case.

executablestaticgetter
static String get executable

The path of the executable used to run the script in this isolate. Usually raya when running on the Raya VM or the compiled script name (script_name.exe).

The literal path used to identify the executable. This path might be relative or just be a name from which the executable was found by searching the system path.

Use resolvedExecutable to get an absolute path to the executable.

resolvedExecutablestaticgetter
static String get resolvedExecutable

The path of the executable used to run the script in this isolate after it has been resolved by the OS.

This is the absolute path, with all symlinks resolved, to the executable used to run the script.

See executable for the unresolved version.

scriptstaticgetter
static Uri get script

The absolute URI of the script being run in this isolate.

If the script argument on the command line is relative, it is resolved to an absolute URI before fetching the script, and that absolute URI is returned.

URI resolution only does string manipulation on the script path, and this may be different from the file system's path resolution behavior. For example, a symbolic link immediately followed by '..' will not be looked up.

If a compiled Raya script is being executed the URI to the compiled script is returned, for example, file:///full/path/to/script_name.exe.

If running on the Raya VM the URI to the running Raya script is returned, for example, file:///full/path/to/script_name.ray.

If the executable environment does not support script, the URI is empty.

static List<String> get executableArguments

The flags passed to the executable used to run the script in this isolate.

These are the command-line flags to the executable that precedes the script name. Provides a new list every time the value is read.

packageConfigstaticgetter
static String? get packageConfig

The --packages flag passed to the executable used to run the script in this isolate.

If present, it specifies a file describing how Raya packages are looked up.

Is null if there is no --packages flag.

lineTerminatorstaticgetter
static String get lineTerminator

The current operating system's default line terminator.

The default character sequence that the operating system uses to separate or terminate text lines.

The line terminator is currently the single line-feed character, U+000A or "\n", on all supported operating systems except Windows, which uses the carriage-return + line-feed sequence, U+000D U+000A or "\r\n"

abstract final class ProcessInfo

Methods for retrieving information about the current process.

Static

currentRssstaticgetter
external static int get currentRss

The current resident set size of memory for the process, in bytes.

Note that the meaning of this field is platform dependent. For example, some memory accounted for here may be shared with other processes, or if the same page is mapped into a process's address space, it may be counted twice.

maxRssstaticgetter
external static int get maxRss

The high-watermark in bytes for the resident set size of memory for the process.

Note that the meaning of this field is platform dependent. For example, some memory accounted for here may be shared with other processes, or if the same page is mapped into a process's address space, it may be counted twice.

final class ProcessStartMode

Modes for running a new process.

Static

normalconstant
static const normal = const ProcessStartMode._internal(0)

Normal child process.

inheritStdioconstant
static const inheritStdio = const ProcessStartMode._internal(1)

Stdio handles are inherited by the child process.

detachedconstant
static const detached = const ProcessStartMode._internal(2)

Detached child process with no open communication channel.

static const detachedWithStdio = const ProcessStartMode._internal(3)

Detached child process with stdin, stdout and stderr still open for communication with the child.

valuesstaticgetter
static List<ProcessStartMode> get values

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  for (final m in ProcessStartMode.values) {
    print(m);
  }
}
Output
normal
inheritStdio
detached
detachedWithStdio
class

Process

abstract interface class Process

The means to execute a program.

Use the static start and run methods to start a new process. The run method executes the process non-interactively to completion. In contrast, the start method allows your code to interact with the running process.

Start a process with the run method

The following code sample uses the run method to create a process that runs the UNIX command ls, which lists the contents of a directory. The run method completes with a ProcessResult object when the process terminates. This provides access to the output and exit code from the process. The run method does not return a Process object; this prevents your code from interacting with the running process.

import 'raya:io';

main() async {
  // List all files in the current directory in UNIX-like systems.
  var result = await Process.run('ls', ['-l']);
  print(result.stdout);
}
Start a process with the start method

The following example uses start to create the process. The start method returns a Future for a Process object. When the future completes the process is started and your code can interact with the process: writing to stdin, listening to stdout, and so on.

The following sample starts the UNIX cat utility, which when given no command-line arguments, echos its input. The program writes to the process's standard input stream and prints data from its standard output stream.

import 'raya:io';
import 'raya:convert';

main() async {
  var process = await Process.start('cat', []);
  process.stdout
      .transform(utf8.decoder)
      .forEach(print);
  process.stdin.writeln('Hello, world!');
  process.stdin.writeln('Hello, galaxy!');
  process.stdin.writeln('Hello, universe!');
}
Standard I/O streams

As seen in the previous code sample, you can interact with the Process's standard output stream through the getter stdout, and you can interact with the Process's standard input stream through the getter stdin. In addition, Process provides a getter stderr for using the Process's standard error stream.

A Process's streams are distinct from the top-level streams for the current program.

NOTE: stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

import 'raya:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}
Exit codes

Call the exitCode method to get the exit code of the process. The exit code indicates whether the program terminated successfully (usually indicated with an exit code of 0) or with an error.

If the start method is used, the exitCode is available through a future on the Process object (as shown in the example below). If the run method is used, the exitCode is available through a getter on the ProcessResult instance.

import 'raya:io';

main() async {
  var process = await Process.start('ls', ['-l']);
  var exitCode = await process.exitCode;
  print('exit code: $exitCode');
}

Static

startstaticmethod
external static Future<Process> start(String executable, List<String> arguments, {String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, ProcessStartMode mode = ProcessStartMode.normal})

Starts a process running the executable with the specified arguments.

Returns a Future<Process> that completes with a Process instance when the process has been successfully started. That Process object can be used to interact with the process. If the process cannot be started the returned Future completes with an exception.

Using an absolute path for executable is recommended since resolving the executable path is platform-specific. On Windows, both any PATH set in the environment map parameter and the path set in workingDirectory parameter are ignored for the purposes of resolving the executable path.

Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.

Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.

If includeParentEnvironment is true, the process's environment will include the parent process's environment, with environment taking precedence. Default is true.

If runInShell is true, the process will be spawned through a system shell. On Linux and OS X, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

NOTE: On Windows, if executable is a batch file ('.bat' or '.cmd'), it may be launched by the operating system in a system shell regardless of the value of runInShell. This could result in arguments being parsed according to shell rules. For example:

void main() async {
  // Will launch notepad.
  Process.start('test.bat', ['test&notepad.exe']);
}

Users must read all data coming on the stdout and stderr streams of processes started with Process.start. If the user does not read all data on the streams the underlying system resources will not be released since there is still pending data.

The following code uses Process.start to grep for main in the file test.ray on Linux.

var process = await Process.start('grep', ['-i', 'main', 'test.ray']);
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);

If mode is ProcessStartMode.normal (the default) a child process will be started with stdin, stdout and stderr connected to its parent. The parent process will not exit so long as the child is running, unless exit is called by the parent. If exit is called by the parent then the parent will be terminated but the child will continue running.

If mode is ProcessStartMode.detached a detached process will be created. A detached process has no connection to its parent, and can keep running on its own when the parent dies. The only information available from a detached process is its pid. There is no connection to its stdin, stdout or stderr, nor will the process' exit code become available when it terminates.

If mode is ProcessStartMode.detachedWithStdio a detached process will be created where the stdin, stdout and stderr are connected. The creator can communicate with the child through these. The detached process will keep running even if these communication channels are closed or the parent dies. The process' exit code will not become available when it terminated.

The default value for mode is ProcessStartMode.normal.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final p = await Process.start('cat', []);
  p.stdin.writeln('sent to cat');
  await p.stdin.close();
  print('cat echoed: ${(await p.stdout.transform(utf8.decoder).join()).trim()}');
  print('exit code: ${await p.exitCode}');
}
Output from the Raya VM
cat echoed: sent to cat
exit code: 0
runstaticmethod
external static Future<ProcessResult> run(String executable, List<String> arguments, {String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding})

Starts a process and runs it non-interactively to completion. The process run is executable with the specified arguments.

Using an absolute path for executable is recommended since resolving the executable path is platform-specific. On Windows, both any PATH set in the environment map parameter and the path set in workingDirectory parameter are ignored for the purposes of resolving the executable path.

Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.

Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.

If includeParentEnvironment is true, the process's environment will include the parent process's environment, with environment taking precedence. Default is true.

If runInShell is true, the process will be spawned through a system shell. On Linux and OS X, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

NOTE: On Windows, if executable is a batch file ('.bat' or '.cmd'), it may be launched by the operating system in a system shell regardless of the value of runInShell. This could result in arguments being parsed according to shell rules. For example:

void main() async {
  // Will launch notepad.
  await Process.run('test.bat', ['test&notepad.exe']);
}

The encoding used for decoding stdout and stderr into text is controlled through stdoutEncoding and stderrEncoding. The default encoding is systemEncoding. If null is used no decoding will happen and the ProcessResult will hold binary data.

Returns a Future<ProcessResult> that completes with the result of running the process, i.e. exit code, standard out and standard error.

The following code uses Process.run to grep for main in the file test.ray on Linux.

var result = await Process.run('grep', ['-i', 'main', 'test.ray']);
stdout.write(result.stdout);
stderr.write(result.stderr);
Example
import 'raya:io';

Future<void> main() async {
  final r = await Process.run('echo', ['hello', 'world']);
  print('stdout: ${(r.stdout as String).trim()}');
  print('exit code: ${r.exitCode}');
  final fail = await Process.run('ls', ['/definitely/not/here']);
  print('failing command exit code is non-zero: ${fail.exitCode != 0}');
}
Output from the Raya VM
stdout: hello world
exit code: 0
failing command exit code is non-zero: true
runSyncstaticmethod
external static ProcessResult runSync(String executable, List<String> arguments, {String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding})

Starts a process and runs it to completion. This is a synchronous call and will block until the child process terminates.

The arguments are the same as for Process.run.

Returns a ProcessResult with the result of running the process, i.e. exit code, standard out and standard error.

Example
import 'raya:io';

void main() {
  final r = Process.runSync('printf', ['%s-%s', 'a', 'b']);
  print('stdout: ${r.stdout}, exit ${r.exitCode}');
  final sh = Process.runSync('sh', ['-c', 'echo out; echo err 1>&2; exit 3']);
  print('stdout: ${(sh.stdout as String).trim()}, stderr: ${(sh.stderr as String).trim()}, exit ${sh.exitCode}');
}
Output from the Raya VM
stdout: a-b, exit 0
stdout: out, stderr: err, exit 3
killPidstaticmethod
external static bool killPid(int pid, [ProcessSignal signal = ProcessSignal.sigterm])

Kills the process with id pid.

Where possible, sends the signal to the process with id pid. This includes Linux and OS X. The default signal is ProcessSignal.sigterm which will normally terminate the process.

On platforms without signal support, including Windows, the call just terminates the process with id pid in a platform specific way, and the signal parameter is ignored.

Returns true if the signal is successfully delivered to the process. Otherwise the signal could not be sent, usually meaning that the process is already dead.

Example
import 'raya:io';

Future<void> main() async {
  final p = await Process.start('sleep', ['30']);
  final killed = Process.killPid(p.pid, ProcessSignal.sigkill);
  print('signal sent: $killed');
  print('exit code: ${await p.exitCode} (minus the signal number)');
}
Output from the Raya VM
signal sent: true
exit code: -9 (minus the signal number)

Properties

exitCodegetter
Future<int> get exitCode

A Future which completes with the exit code of the process when the process completes.

The exit code is not available for processes running with ProcessStartMode.detached or ProcessStartMode.detachedWithStdio and the getter will throw StateError if it is used.

The handling of exit codes is platform specific.

On Linux and OS X a normal exit code will be a positive value in the range [0..255]. If the process was terminated due to a signal the exit code will be a negative value in the range [-255..-1], where the absolute value of the exit code is the signal number. For example, if a process crashes due to a segmentation violation the exit code will be -11, as the signal SIGSEGV has the number 11.

On Windows a process can report any 32-bit value as an exit code. When returning the exit code this exit code is turned into a signed value. Some special values are used to report termination due to some system event. E.g. If a process crashes due to an access violation the 32-bit exit code is 0xc0000005, which will be returned as the negative number -1073741819. To get the original 32-bit value use (0x100000000 + exitCode) & 0xffffffff.

There is no guarantee that stdout and stderr have finished reporting the buffered output of the process when the returned future completes. To be sure that all output is captured, wait for the done event on the streams.

stdoutgetter
Stream<List<int>> get stdout

The standard output stream of the process as a Stream.

NOTE: stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

import 'raya:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}
stderrgetter
Stream<List<int>> get stderr

The standard error stream of the process as a Stream.

NOTE: stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

import 'raya:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}
stdingetter
IOSink get stdin

The standard input stream of the process as an IOSink.

pidgetter
int get pid

The process id of the process.

Methods

killmethod
bool kill([ProcessSignal signal = ProcessSignal.sigterm])

Kills the process.

Where possible, sends the signal to the process. This includes Linux and OS X. The default signal is ProcessSignal.sigterm which will normally terminate the process.

On platforms without signal support, including Windows, the call just terminates the process in a platform specific way, and the signal parameter is ignored.

Returns true if the signal is successfully delivered to the process. Otherwise the signal could not be sent, usually meaning that the process is already dead.

Example
import 'raya:io';

Future<void> main() async {
  final p = await Process.start('sleep', ['30']);
  print('kill(): ${p.kill()}');
  print('exit code: ${await p.exitCode} (terminated by SIGTERM)');
}
Output from the Raya VM
kill(): true
exit code: -15 (terminated by SIGTERM)
final class ProcessResult

The result of running a non-interactive process started with Process.run or Process.runSync.

Constructors

ProcessResultconstructor
ProcessResult(this.pid, this.exitCode, this.stdout, this.stderr)
Example
import 'raya:io';

void main() {
  // Handy when faking Process.run in tests.
  final r = ProcessResult(1234, 0, 'fake output', '');
  print('pid ${r.pid}, exitCode ${r.exitCode}, stdout "${r.stdout}"');
}
Output
pid 1234, exitCode 0, stdout "fake output"

Properties

final int exitCode

Exit code for the process.

See Process.exitCode for more information in the exit code value.

stdoutfield
final stdout

Standard output from the process.

The value used for the stdoutEncoding argument to Process.run determines the type. If null was used, this value is of type Uint8List otherwise it is of type String.

stderrfield
final stderr

Standard error from the process.

The value used for the stderrEncoding argument to Process.run determines the type. If null was used, this value is of type Uint8List otherwise it is of type String.

pidfield
final int pid

Process id of the process.

interface class ProcessSignal

On Posix systems, ProcessSignal is used to send a specific signal to a child process, see Process.kill.

Some ProcessSignals can also be watched, as a way to intercept the default signal handler and implement another. See ProcessSignal.watch for more information.

Static

sighupconstant
static const ProcessSignal sighup = const ProcessSignal._(1, "SIGHUP")
sigintconstant
static const ProcessSignal sigint = const ProcessSignal._(2, "SIGINT")
sigquitconstant
static const ProcessSignal sigquit = const ProcessSignal._(3, "SIGQUIT")
sigillconstant
static const ProcessSignal sigill = const ProcessSignal._(4, "SIGILL")
sigtrapconstant
static const ProcessSignal sigtrap = const ProcessSignal._(5, "SIGTRAP")
sigabrtconstant
static const ProcessSignal sigabrt = const ProcessSignal._(6, "SIGABRT")
sigbusconstant
static const ProcessSignal sigbus = const ProcessSignal._(7, "SIGBUS")
sigfpeconstant
static const ProcessSignal sigfpe = const ProcessSignal._(8, "SIGFPE")
sigkillconstant
static const ProcessSignal sigkill = const ProcessSignal._(9, "SIGKILL")
sigusr1constant
static const ProcessSignal sigusr1 = const ProcessSignal._(10, "SIGUSR1")
sigsegvconstant
static const ProcessSignal sigsegv = const ProcessSignal._(11, "SIGSEGV")
sigusr2constant
static const ProcessSignal sigusr2 = const ProcessSignal._(12, "SIGUSR2")
sigpipeconstant
static const ProcessSignal sigpipe = const ProcessSignal._(13, "SIGPIPE")
sigalrmconstant
static const ProcessSignal sigalrm = const ProcessSignal._(14, "SIGALRM")
sigtermconstant
static const ProcessSignal sigterm = const ProcessSignal._(15, "SIGTERM")
sigchldconstant
static const ProcessSignal sigchld = const ProcessSignal._(17, "SIGCHLD")
sigcontconstant
static const ProcessSignal sigcont = const ProcessSignal._(18, "SIGCONT")
sigstopconstant
static const ProcessSignal sigstop = const ProcessSignal._(19, "SIGSTOP")
sigtstpconstant
static const ProcessSignal sigtstp = const ProcessSignal._(20, "SIGTSTP")
sigttinconstant
static const ProcessSignal sigttin = const ProcessSignal._(21, "SIGTTIN")
sigttouconstant
static const ProcessSignal sigttou = const ProcessSignal._(22, "SIGTTOU")
sigurgconstant
static const ProcessSignal sigurg = const ProcessSignal._(23, "SIGURG")
sigxcpuconstant
static const ProcessSignal sigxcpu = const ProcessSignal._(24, "SIGXCPU")
sigxfszconstant
static const ProcessSignal sigxfsz = const ProcessSignal._(25, "SIGXFSZ")
sigvtalrmconstant
static const ProcessSignal sigvtalrm = const ProcessSignal._(26, "SIGVTALRM")
sigprofconstant
static const ProcessSignal sigprof = const ProcessSignal._(27, "SIGPROF")
sigwinchconstant
static const ProcessSignal sigwinch = const ProcessSignal._(28, "SIGWINCH")
sigpollconstant
static const ProcessSignal sigpoll = const ProcessSignal._(29, "SIGPOLL")
sigsysconstant
static const ProcessSignal sigsys = const ProcessSignal._(31, "SIGSYS")

Properties

final int signalNumber

The numeric constant for the signal e.g. ProcessSignal.signalNumber will be 1 for ProcessSignal.sighup on most platforms.

namefield
final String name

The POSIX-standardized name of the signal e.g. ProcessSignal.name will be "SIGHUP" for ProcessSignal.sighup.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(ProcessSignal.sigint);
  print(ProcessSignal.sigterm);
  print('sigkill number: ${ProcessSignal.sigkill.signalNumber}');
}
Output
SIGINT
SIGTERM
sigkill number: 9
watchmethod
Stream<ProcessSignal> watch()

Watch for process signals.

The following ProcessSignals can be listened to:

Other signals are disallowed, as they may be used by the VM.

A signal can be watched multiple times, from multiple isolates, where all callbacks are invoked when signaled, in no specific order.

Example
import 'raya:io';

Future<void> main() async {
  final events = ProcessSignal.sigusr1.watch();
  final got = events.first;
  Process.killPid(pid, ProcessSignal.sigusr1); // signal ourselves
  print('received: ${await got}');
}
Output from the Raya VM
received: SIGUSR1
class SignalException implements IOException

Constructors

SignalExceptionconstructor
const SignalException(this.message, [this.osError])
Example
import 'raya:io';

void main() {
  const e = SignalException('Failed to listen for SIGHUP', OSError('Invalid argument', 22));
  print('message: ${e.message}, errno: ${e.osError?.errorCode}');
}
Output
message: Failed to listen for SIGHUP, errno: 22

Properties

messagefield
final String message
osErrorfield
final osError

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const SignalException('Cannot watch signal'));
}
Output
SignalException: Cannot watch signal
class ProcessException implements IOException

Constructors

ProcessExceptionconstructor
const ProcessException(this.executable, this.arguments, [this.message = "", this.errorCode = 0])
Example
import 'raya:io';

void main() {
  try {
    Process.runSync('no-such-program-xyz', ['--help']);
  } on ProcessException catch (e) {
    print('executable: ${e.executable}, arguments: ${e.arguments}');
  }
}
Output from the Raya VM
executable: no-such-program-xyz, arguments: [--help]

Properties

final String executable

The executable provided for the process.

final List<String> arguments

The arguments provided for the process.

messagefield
final String message

The system message for the process exception, if any.

The empty string if no message was available.

final int errorCode

The OS error code for the process exception, if any.

The value is zero if no OS error code was available.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const ProcessException('git', ['status'], 'not a repository', 128));
}
Output
ProcessException: not a repository
  Command: git status
class SecureServerSocket extends Stream<SecureSocket> implements ServerSocketBase<SecureSocket>

A server socket, providing a stream of high-level Sockets.

See SecureSocket for more info.

Static

bindstaticmethod
static Future<SecureServerSocket> bind(address, int port, SecurityContext? context, {int backlog = 0, bool v6Only = false, bool requestClientCertificate = false, bool requireClientCertificate = false, List<String>? supportedProtocols, bool shared = false})

Listens on a given address and port.

When the returned future completes, the server socket is bound to the given address and port and has started listening on it.

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If port has the value 0, an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

Incoming client connections are promoted to secure connections, using the server certificate and key set in context.

The address must be given as a numeric address, not a host name.

To request or require that clients authenticate by providing an SSL (TLS) client certificate, set the optional parameter requestClientCertificate or requireClientCertificate to true. Requiring a certificate implies requesting a certificate, so setting both is redundant. To check whether a client certificate was received, check SecureSocket.peerCertificate after connecting. If no certificate was received, the result will be null.

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with clients. Example values are "http/1.1" or "h2". The selected protocol can be obtained via SecureSocket.selectedProtocol.

The optional argument shared specifies whether additional SecureServerSocket objects can bind to the same combination of address, port and v6Only. If shared is true and more SecureServerSockets from this isolate or other isolates are bound to the same port, then the incoming connections will be distributed among all the bound SecureServerSockets. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s..write('encrypted hello')..close()..drain<void>());
  final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  print('${String.fromCharCodes(await s.expand((c) => c).toList())}, cert subject ${s.peerCertificate?.subject}');
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
encrypted hello, cert subject /CN=localhost

Properties

portgetter
int get port

The port used by this socket.

addressgetter
InternetAddress get address

The address used by this socket.

Methods

listenmethod
StreamSubscription<SecureSocket> listen(void onData(SecureSocket socket)?, {Function? onError, void onDone()?, bool? cancelOnError})
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((SecureSocket s) {
    s.listen((data) => s..write('upper: ${utf8.decode(data).toUpperCase()}')..close());
  });
  final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  s.write('secret');
  print(await utf8.decoder.bind(s).join().timeout(const Duration(seconds: 2)));
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
upper: SECRET
closemethod
Future<SecureServerSocket> close()

Closes this socket.

The returned future completes when the socket is fully closed and is no longer bound.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  final done = server.drain<void>();
  await server.close();
  await done;
  print('secure server closed; its connection stream finished');
  d.deleteSync(recursive: true);
}
Output from the Raya VM
secure server closed; its connection stream finished
class RawSecureServerSocket extends Stream<RawSecureSocket>

A server socket providing a stream of low-level RawSecureSockets.

See RawSecureSocket for more info.

Static

bindstaticmethod
static Future<RawSecureServerSocket> bind(address, int port, SecurityContext? context, {int backlog = 0, bool v6Only = false, bool requestClientCertificate = false, bool requireClientCertificate = false, List<String>? supportedProtocols, bool shared = false})

Listens on a provided address and port.

When the returned future completes, the server socket is bound to the given address and port and has started listening on it.

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

Incoming client connections are promoted to secure connections, using the server certificate and key set in context.

address must be given as a numeric address, not a host name.

To request or require that clients authenticate by providing an SSL (TLS) client certificate, set the optional parameters requestClientCertificate or requireClientCertificate to true. Require implies request, so one doesn't need to specify both. To check whether a client certificate was received, check SecureSocket.peerCertificate after connecting. If no certificate was received, the result will be null.

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with clients. Example values are "http/1.1" or "h2". The selected protocol can be obtained via RawSecureSocket.selectedProtocol.

The optional argument shared specifies whether additional RawSecureServerSocket objects can bind to the same combination of address, port and v6Only. If shared is true and more RawSecureServerSockets from this isolate or other isolates are bound to the port, then the incoming connections will be distributed among all the bound RawSecureServerSockets. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await RawSecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((RawSecureSocket raw) {
    raw.write([1, 2, 3]);
    raw.close();
  });
  final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  print('received over TLS: ${await s.expand((c) => c).toList()}');
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
received over TLS: [1, 2, 3]

Properties

final bool requestClientCertificate
final bool requireClientCertificate
final List<String>? supportedProtocols
portgetter
int get port

The port used by this socket.

addressgetter
InternetAddress get address

The address used by this socket.

Methods

listenmethod
StreamSubscription<RawSecureSocket> listen(void onData(RawSecureSocket s)?, {Function? onError, void onDone()?, bool? cancelOnError})
Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await RawSecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  var connections = 0;
  server.listen((raw) {
    connections++;
    raw.close();
  });
  for (var i = 0; i < 2; i++) {
    final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
    await s.drain<void>();
    s.destroy();
  }
  print('handshakes completed: $connections');
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
handshakes completed: 2
closemethod
Future<RawSecureServerSocket> close()

Closes this socket.

The returned future completes when the socket is fully closed and is no longer bound.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await RawSecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  final port = server.port;
  await server.close();
  try {
    await Socket.connect(InternetAddress.loopbackIPv4, port).timeout(const Duration(seconds: 2));
  } on SocketException {
    print('closed: connections refused');
  }
  d.deleteSync(recursive: true);
}
Output from the Raya VM
closed: connections refused
abstract interface class SecureSocket implements Socket

A TCP socket using TLS and SSL.

See Socket for more information.

Static

connectstaticmethod
static Future<SecureSocket> connect(host, int port, {SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols, Duration? timeout})

Constructs a new secure client socket and connects it to the given host on port port.

The returned Future will complete with a SecureSocket that is connected and ready for subscription.

The certificate provided by the server is checked using the trusted certificates set in the SecurityContext object. The default SecurityContext object contains a built-in set of trusted root certificates for well-known certificate authorities.

onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the SecureSocket connection.

keyLog is an optional callback that will be called when new TLS keys are exchanged with the server. keyLog will receive one line of text in [NSS Key Log Format] for each call. Writing these lines to a file will allow tools (such as Wireshark) to decrypt content sent through this socket. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:

final log = File('keylog.txt');
final socket = await SecureSocket.connect('www.example.com', 443,
    keyLog: (line) => log.writeAsStringSync(line, mode: FileMode.append));

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with the server. Example values are "http/1.1" or "h2". The selected protocol can be obtained via SecureSocket.selectedProtocol.

The argument timeout is used to specify the maximum allowed time to wait for a connection to be established. If timeout is longer than the system level timeout duration, a timeout may occur sooner than specified in timeout. On timeout, a SocketException is thrown and all ongoing connection attempts to host are cancelled.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s..write('hi')..close()..drain<void>());
  final rejected = <String>[];
  final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (cert) {
    rejected.add(cert.subject); // self-signed, so verification fails; accept it anyway
    return true;
  }).timeout(const Duration(seconds: 2));
  print('accepted untrusted cert: $rejected, got ${String.fromCharCodes(await s.expand((c) => c).toList())}');
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
accepted untrusted cert: [/CN=localhost], got hi
startConnectstaticmethod
static Future<ConnectionTask<SecureSocket>> startConnect(host, int port, {SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols})

Like connect, but returns a Future that completes with a ConnectionTask that can be cancelled if the SecureSocket is no longer needed.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s..write('started')..close()..drain<void>());
  final task = await SecureSocket.startConnect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  final s = await task.socket.timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await s.expand((c) => c).toList()));
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
started
securestaticmethod
static Future<SecureSocket> secure(Socket socket, {host, SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols})

Initiates TLS on an existing connection.

Takes an already connected socket and starts client side TLS handshake to make the communication secure. When the returned future completes the SecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is prepared for TLS handshake.

If the socket already has a subscription, this subscription will no longer receive and events. In most cases calling StreamSubscription.pause on this subscription before starting TLS handshake is the right thing to do.

The given socket is closed and may not be used anymore.

If the host argument is passed it will be used as the host name for the TLS handshake. If host is not passed the host name from the socket will be used. The host can be either a String or an InternetAddress.

onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the SecureSocket connection.

keyLog is an optional callback that will be called when new TLS keys are exchanged with the server. keyLog will receive one line of text in [NSS Key Log Format] for each call. Writing these lines to a file will allow tools (such as Wireshark) to decrypt content sent through this socket. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:

final log = File('keylog.txt');
final socket = await SecureSocket.connect('www.example.com', 443,
    keyLog: (line) => log.writeAsStringSync(line, mode: FileMode.append));

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with the server. Example values are "http/1.1" or "h2". The selected protocol can be obtained via SecureSocket.selectedProtocol.

Calling this function will not cause a DNS host lookup. If the host passed is a String, the InternetAddress for the resulting SecureSocket will have the passed in host as its host value and the internet address of the already connected socket as its address value.

See connect for more information on the arguments.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  final plain = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  plain.listen((s) async {
    final tls = await SecureSocket.secureServer(s, ctx);
    tls..write('upgraded to TLS')..close()..drain<void>();
  });
  final s = await Socket.connect(InternetAddress.loopbackIPv4, plain.port).timeout(const Duration(seconds: 2));
  final tls = await SecureSocket.secure(s, host: 'localhost', onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await tls.expand((c) => c).toList()));
  tls.destroy();
  await plain.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
upgraded to TLS
secureServerstaticmethod
static Future<SecureSocket> secureServer(Socket socket, SecurityContext? context, {List<int>? bufferedData, bool requestClientCertificate = false, bool requireClientCertificate = false, List<String>? supportedProtocols})

Initiates TLS on an existing server connection.

Takes an already connected socket and starts server side TLS handshake to make the communication secure. When the returned future completes the SecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is going to start the TLS handshake.

If the socket already has a subscription, this subscription will no longer receive and events. In most cases calling StreamSubscription.pause on this subscription before starting TLS handshake is the right thing to do.

If some of the data of the TLS handshake has already been read from the socket this data can be passed in the bufferedData parameter. This data will be processed before any other data available on the socket.

See SecureServerSocket.bind for more information on the arguments.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  final plain = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  plain.listen((s) async {
    // Like STARTTLS: begin in plain text, then switch the socket to TLS.
    final tls = await SecureSocket.secureServer(s, ctx);
    tls..write('server side of TLS')..close()..drain<void>();
  });
  final s = await Socket.connect(InternetAddress.loopbackIPv4, plain.port).timeout(const Duration(seconds: 2));
  final tls = await SecureSocket.secure(s, host: 'localhost', onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await tls.expand((c) => c).toList()));
  tls.destroy();
  await plain.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
server side of TLS

Properties

X509Certificate? get peerCertificate

The peer certificate for a connected SecureSocket.

If this SecureSocket is the server end of a secure socket connection, peerCertificate will return the client certificate, or null if no client certificate was received. If this socket is the client end, peerCertificate will return the server's certificate.

String? get selectedProtocol

The protocol which was selected during ALPN protocol negotiation.

Returns null if one of the peers does not have support for ALPN, did not specify a list of supported ALPN protocols or there was no common protocol between client and server.

Methods

renegotiatemethoddeprecated
void renegotiate({bool useSessionCache = true, bool requestClientCertificate = false, bool requireClientCertificate = false})

Does nothing.

The original intent was to allow TLS renegotiation of existing secure connections.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) {
    try {
      s.renegotiate(requestClientCertificate: true);
      print('renegotiate called');
    } on UnsupportedError catch (e) {
      print('renegotiate: ${e.message}');
    }
    s.destroy();
  });
  final s = await SecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  await s.drain<void>().timeout(const Duration(seconds: 2));
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
renegotiate called
abstract interface class RawSecureSocket implements RawSocket

RawSecureSocket provides a secure (SSL or TLS) network connection.

Client connections to a server are provided by calling RawSecureSocket.connect. A secure server, created with RawSecureServerSocket, also returns RawSecureSocket objects representing the server end of a secure connection. The certificate provided by the server is checked using the trusted certificates set in the SecurityContext object. The default SecurityContext object contains a built-in set of trusted root certificates for well-known certificate authorities.

See RawSocket for more information.

Static

connectstaticmethod
static Future<RawSecureSocket> connect(host, int port, {SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols, Duration? timeout})

Constructs a new secure client socket and connect it to the given host on the given port.

The returned Future is completed with the RawSecureSocket when it is connected and ready for subscription.

The certificate provided by the server is checked using the trusted certificates set in the SecurityContext object If a certificate and key are set on the client, using SecurityContext.useCertificateChain and SecurityContext.usePrivateKey, and the server asks for a client certificate, then that client certificate is sent to the server.

onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the RawSecureSocket connection.

onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the SecureSocket connection.

keyLog is an optional callback that will be called when new TLS keys are exchanged with the server. keyLog will receive one line of text in [NSS Key Log Format] for each call. Writing these lines to a file will allow tools (such as Wireshark) to decrypt content sent through this socket. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:

final log = File('keylog.txt');
final socket = await SecureSocket.connect('www.example.com', 443,
    keyLog: (line) => log.writeAsStringSync(line, mode: FileMode.append));

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with the server. Example values are "http/1.1" or "h2". The selected protocol can be obtained via RawSecureSocket.selectedProtocol.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s..add([4, 5, 6])..close()..drain<void>());
  final raw = await RawSecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  final got = <int>[];
  await for (final e in raw) {
    if (e == RawSocketEvent.read) got.addAll(raw.read() ?? []);
    if (e == RawSocketEvent.readClosed) raw.close();
  }
  print('decrypted bytes: $got');
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
decrypted bytes: [4, 5, 6]
startConnectstaticmethod
static Future<ConnectionTask<RawSecureSocket>> startConnect(host, int port, {SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols})

Like connect, but returns a Future that completes with a ConnectionTask that can be cancelled if the RawSecureSocket is no longer needed.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s.destroy());
  final task = await RawSecureSocket.startConnect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  final raw = await task.socket.timeout(const Duration(seconds: 2));
  print('handshake done; peer cert subject: ${raw.peerCertificate?.subject}');
  await raw.close();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
handshake done; peer cert subject: /CN=localhost
securestaticmethod
static Future<RawSecureSocket> secure(RawSocket socket, {StreamSubscription<RawSocketEvent>? subscription, host, SecurityContext? context, bool onBadCertificate(X509Certificate certificate)?, void keyLog(String line)?, List<String>? supportedProtocols})

Initiates TLS on an existing connection.

Takes an already connected socket and starts client side TLS handshake to make the communication secure. When the returned future completes the RawSecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is prepared for TLS handshake.

If the socket already has a subscription, pass the existing subscription in the subscription parameter. The secure operation will take over the subscription by replacing the handlers with it own secure processing. The caller must not touch this subscription anymore. Passing a paused subscription is an error.

If the host argument is passed it will be used as the host name for the TLS handshake. If host is not passed the host name from the socket will be used. The host can be either a String or an InternetAddress.

onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the SecureSocket connection.

keyLog is an optional callback that will be called when new TLS keys are exchanged with the server. keyLog will receive one line of text in [NSS Key Log Format] for each call. Writing these lines to a file will allow tools (such as Wireshark) to decrypt content sent through this socket. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:

final log = File('keylog.txt');
final socket = await SecureSocket.connect('www.example.com', 443,
    keyLog: (line) => log.writeAsStringSync(line, mode: FileMode.append));

supportedProtocols is an optional list of protocols (in decreasing order of preference) to use during the ALPN protocol negotiation with the server. Example values are "http/1.1" or "h2". The selected protocol can be obtained via SecureSocket.selectedProtocol.

Calling this function will not cause a DNS host lookup. If the host passed is a String the InternetAddress for the resulting SecureSocket will have this passed in host as its host value and the internet address of the already connected socket as its address value.

See connect for more information on the arguments.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  final plain = await RawServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  plain.listen((raw) async {
    final tls = await RawSecureSocket.secureServer(raw, ctx);
    tls.write([9, 9]);
    await tls.close();
  });
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, plain.port).timeout(const Duration(seconds: 2));
  final tls = await RawSecureSocket.secure(raw, host: 'localhost', onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  final got = <int>[];
  await for (final e in tls) {
    if (e == RawSocketEvent.read) got.addAll(tls.read() ?? []);
    if (e == RawSocketEvent.readClosed) tls.close();
  }
  print('read after upgrading a raw socket: $got');
  await plain.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
read after upgrading a raw socket: [9, 9]
secureServerstaticmethod
static Future<RawSecureSocket> secureServer(RawSocket socket, SecurityContext? context, {StreamSubscription<RawSocketEvent>? subscription, List<int>? bufferedData, bool requestClientCertificate = false, bool requireClientCertificate = false, List<String>? supportedProtocols})

Initiates TLS on an existing server connection.

Takes an already connected socket and starts server side TLS handshake to make the communication secure. When the returned future completes the RawSecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is going to start the TLS handshake.

If the socket already has a subscription, pass the existing subscription in the subscription parameter. The secureServer operation will take over the subscription by replacing the handlers with it own secure processing. The caller must not touch this subscription anymore. Passing a paused subscription is an error.

If some of the data of the TLS handshake has already been read from the socket this data can be passed in the bufferedData parameter. This data will be processed before any other data available on the socket.

See RawSecureServerSocket.bind for more information on the arguments.

Example
import 'raya:io';
import 'raya:async';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  final plain = await RawServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final served = Completer<void>();
  plain.listen((raw) async {
    final tls = await RawSecureSocket.secureServer(raw, ctx);
    print('server handshake complete: ${tls.selectedProtocol == null ? 'no ALPN' : tls.selectedProtocol}');
    await tls.close();
    served.complete();
  });
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, plain.port).timeout(const Duration(seconds: 2));
  final tls = await RawSecureSocket.secure(raw, host: 'localhost', onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  await served.future.timeout(const Duration(seconds: 2));
  await tls.close();
  await plain.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
server handshake complete: no ALPN

Properties

X509Certificate? get peerCertificate

Get the peer certificate for a connected RawSecureSocket. If this RawSecureSocket is the server end of a secure socket connection, peerCertificate will return the client certificate, or null, if no client certificate was received. If it is the client end, peerCertificate will return the server's certificate.

String? get selectedProtocol

The protocol which was selected during protocol negotiation.

Returns null if one of the peers does not have support for ALPN, did not specify a list of supported ALPN protocols or there was no common protocol between client and server.

Methods

renegotiatemethoddeprecated
void renegotiate({bool useSessionCache = true, bool requestClientCertificate = false, bool requireClientCertificate = false})

Does nothing.

The original intent was to allow TLS renegotiation of existing secure connections.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s.destroy());
  final raw = await RawSecureSocket.connect('localhost', server.port, onBadCertificate: (_) => true).timeout(const Duration(seconds: 2));
  try {
    raw.renegotiate();
    print('renegotiate called');
  } on UnsupportedError catch (e) {
    print('renegotiate: ${e.message}');
  }
  await raw.close();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
renegotiate called
abstract interface class X509Certificate

X509Certificate represents an SSL certificate, with accessors to get the fields of the certificate.

Properties

dergetter
Uint8List get der

The DER encoded bytes of the certificate.

pemgetter
String get pem

The PEM encoded String of the certificate.

sha1getter
Uint8List get sha1

The SHA1 hash of the certificate.

subjectgetter
String get subject
issuergetter
String get issuer
DateTime get startValidity
DateTime get endValidity
class TlsException implements IOException

A secure networking exception caused by a failure in the TLS/SSL protocol.

Constructors

TlsExceptionconstructor
const TlsException([String message = "", OSError? osError])
Example
import 'raya:io';

void main() {
  const e = TlsException('Bad record MAC');
  print('message: ${e.message}, is IOException: ${e is IOException}');
  print(e);
}
Output
message: Bad record MAC, is IOException: true
TlsException: Bad record MAC

Properties

typefield
final String type
messagefield
final String message
osErrorfield
final OSError? osError

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const TlsException('Bad certificate', OSError('CERTIFICATE_VERIFY_FAILED', 1)));
  print(const HandshakeException('Handshake error'));
}
Output
TlsException: Bad certificate (OS Error: CERTIFICATE_VERIFY_FAILED, errno = 1)
HandshakeException: Handshake error
class HandshakeException extends TlsException

An exception that happens in the handshake phase of establishing a secure network connection.

Constructors

const HandshakeException([String message = "", OSError? osError])
Example
import 'raya:io';

void main() {
  const e = HandshakeException('Connection terminated during handshake');
  print('is a TlsException: ${e is TlsException}');
  print(e);
}
Output
is a TlsException: true
HandshakeException: Connection terminated during handshake
class CertificateException extends TlsException

An exception that happens in the handshake phase of establishing a secure network connection, when looking up or verifying a certificate.

Constructors

const CertificateException([String message = "", OSError? osError])
Example
import 'raya:io';

void main() {
  const e = CertificateException('Certificate has expired');
  print(e);
  print('caught as TlsException: ${e is TlsException}');
}
Output
CertificateException: Certificate has expired
caught as TlsException: true
class TlsProtocolVersion

A Transport Layer Security (TLS) version.

Only TLS versions supported by raya:io are included.

Static

tls1_2constant
static const tls1_2 = TlsProtocolVersion._(0x0303)

Transport Layer Security (TLS) Protocol Version 1.2.

See RFC-5246.

tls1_3constant
static const tls1_3 = TlsProtocolVersion._(0x0304)

Transport Layer Security (TLS) Protocol Version 1.3.

See RFC-8446.

abstract final class SecurityContext

The object containing the certificates to trust when making a secure client connection, and the certificate chain and private key to serve from a secure server.

The SecureSocket and SecureServerSocket classes take a SecurityContext as an argument to their connect and bind methods.

Certificates and keys can be added to a SecurityContext from either PEM or PKCS12 containers.

iOS note: Some methods to add, remove, and inspect certificates are not yet implemented. However, the platform's built-in trusted certificates can be used, by way of SecurityContext.defaultContext.

Constructors

external factory SecurityContext({bool withTrustedRoots = false})

Creates a new SecurityContext.

By default, the created SecurityContext contains no keys or certificates. These can be added by calling the methods of this class.

If withTrustedRoots is passed as true, the SecurityContext will be seeded by the trusted root certificates provided as explained below. To obtain a SecurityContext containing trusted root certificates, SecurityContext.defaultContext is usually sufficient, and should be used instead. However, if the SecurityContext containing the trusted root certificates must be modified per-connection, then withTrustedRoots should be used.

Example
import 'raya:io';

void main() {
  final empty = SecurityContext();
  final trusted = SecurityContext(withTrustedRoots: true);
  print('contexts created: ${empty != trusted}');
  print('ALPN supported: ${SecurityContext.alpnSupported}');
}
Output from the Raya VM
contexts created: true
ALPN supported: true

Static

defaultContextstaticgetter
external static SecurityContext get defaultContext

The default security context used by most operation requiring one.

Secure networking classes with an optional context parameter use the defaultContext object if the parameter is omitted. This object can also be accessed, and modified, directly. Each isolate has a different defaultContext object. The defaultContext object uses a list of well-known trusted certificate authorities as its trusted roots. On Linux and Windows, this list is taken from Mozilla, who maintains it as part of Firefox. On, MacOS, iOS, and Android, this list comes from the trusted certificates stores built into the platforms.

alpnSupportedstaticgetterdeprecated
external static bool get alpnSupported

Whether the platform supports ALPN. This always returns true and will be removed in a future release.

Properties

abstract bool allowLegacyUnsafeRenegotiation

If true, the SecurityContext will allow TLS renegotiation. Renegotiation is only supported as a client and the HelloRequest must be received at a quiet point in the application protocol. This is sufficient to support the legacy use case of requesting a new client certificate between an HTTP request and response in (unpipelined) HTTP/1.1. NOTE: Renegotiation is an extremely problematic protocol feature and should only be used to communicate with legacy servers in environments where it is known to be safe.

abstract TlsProtocolVersion minimumTlsProtocolVersion

The minimum TLS version to use when establishing a secure connection.

If the peer does not support minimumTlsProtocolVersion or later then SecureSocket.connect will throw a TlsException.

If the value is changed, it will only affect new connections. Existing connections will continue to use the protocol that was negotiated with the peer.

The default value is TlsProtocolVersion.tls1_2.

Methods

void usePrivateKey(String file, {String? password})

Sets the private key for a server certificate or client certificate.

A secure connection using this SecurityContext will use this key with the server or client certificate to sign and decrypt messages. file is the path to a PEM or PKCS12 file containing an encrypted private key, encrypted with password. Assuming it is well-formatted, all other contents of file are ignored. An unencrypted file can be used, but this is not usual.

NB: This function calls File.readAsBytesSync, and will block on file IO. Prefer using usePrivateKeyBytes.

iOS note: Only PKCS12 data is supported. It should contain both the private key and the certificate chain. On iOS one call to usePrivateKey with this data is used instead of two calls to useCertificateChain and usePrivateKey.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = SecurityContext()..useCertificateChain('${d.path}/c.pem');
  ctx.usePrivateKey('${d.path}/k.pem'); // the key matching the certificate
  print('key loaded');
  try {
    SecurityContext().usePrivateKey('${d.path}/c.pem'); // a certificate is not a key
  } on ArgumentError {
    print('wrong file: ArgumentError (no private key found)');
  }
  d.deleteSync(recursive: true);
}
Output from the Raya VM
key loaded
wrong file: ArgumentError (no private key found)
void usePrivateKeyBytes(List<int> keyBytes, {String? password})

Sets the private key for a server certificate or client certificate.

Like usePrivateKey, but takes the contents of the file as a list of bytes.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  // Keys can come from memory, e.g. a secrets store, instead of a file.
  final keyBytes = File('${d.path}/k.pem').readAsBytesSync();
  final ctx = SecurityContext()
    ..useCertificateChainBytes(File('${d.path}/c.pem').readAsBytesSync())
    ..usePrivateKeyBytes(keyBytes);
  final s = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, ctx);
  print('server context built from ${keyBytes.length > 0 ? 'in-memory' : 'empty'} key bytes');
  await s.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
server context built from in-memory key bytes
void setTrustedCertificates(String file, {String? password})

Add a certificate to the set of trusted X509 certificates used by SecureSocket client connections.

file is the path to a PEM or PKCS12 file containing X509 certificates, usually root certificates from certificate authorities. For PKCS12 files, password is the password for the file. For PEM files, password is ignored. Assuming it is well-formatted, all other contents of file are ignored.

NB: This function calls File.readAsBytesSync, and will block on file IO. Prefer using setTrustedCertificatesBytes.

iOS note: On iOS, this call takes only the bytes for a single DER encoded X509 certificate. It may be called multiple times to add multiple trusted certificates to the context. A DER encoded certificate can be obtained from a PEM encoded certificate by using the openssl tool:

$ openssl x509 -outform der -in cert.pem -out cert.der
Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((s) => s..write('trusted hello')..close()..drain<void>());
  // Trust our self-signed certificate, so no onBadCertificate is needed.
  final client = SecurityContext()..setTrustedCertificates('${d.path}/c.pem');
  final s = await SecureSocket.connect('localhost', server.port, context: client).timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await s.expand((c) => c).toList()));
  s.destroy();
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
trusted hello
void setTrustedCertificatesBytes(List<int> certBytes, {String? password})

Add a certificate to the set of trusted X509 certificates used by SecureSocket client connections.

Like setTrustedCertificates but takes the contents of the file.

Example
import 'raya:io';
import 'raya:convert';

void main() {
  final ctx = SecurityContext();
  try {
    ctx.setTrustedCertificatesBytes(utf8.encode('not a certificate'));
  } on TlsException catch (e) {
    print('rejected: ${e.runtimeType}');
  }
}
Output from the Raya VM
rejected: TlsException
void useCertificateChain(String file, {String? password})

Sets the chain of X509 certificates served by SecureServerSocket when making secure connections, including the server certificate.

file is a PEM or PKCS12 file containing X509 certificates, starting with the root authority and intermediate authorities forming the signed chain to the server certificate, and ending with the server certificate. The private key for the server certificate is set by usePrivateKey. For PKCS12 files, password is the password for the file. For PEM files, password is ignored. Assuming it is well-formatted, all other contents of file are ignored.

NB: This function calls File.readAsBytesSync, and will block on file IO. Prefer using useCertificateChainBytes.

iOS note: As noted above, usePrivateKey does the job of both that call and this one. On iOS, this call is a no-op.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = SecurityContext()
    ..useCertificateChain('${d.path}/c.pem')
    ..usePrivateKey('${d.path}/k.pem');
  final s = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, server);
  print('TLS server listening with the certificate chain loaded');
  await s.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
TLS server listening with the certificate chain loaded
void useCertificateChainBytes(List<int> chainBytes, {String? password})

Sets the chain of X509 certificates served by SecureServerSocket when making secure connections, including the server certificate.

Like useCertificateChain but takes the contents of the file.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final pem = File('${d.path}/c.pem').readAsStringSync();
  print('PEM starts with: ${pem.split('\n').first}');
  final ctx = SecurityContext()
    ..useCertificateChainBytes(pem.codeUnits)
    ..usePrivateKey('${d.path}/k.pem');
  await (await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, ctx)).close().timeout(const Duration(seconds: 2));
  print('chain accepted from bytes');
  d.deleteSync(recursive: true);
}
Output from the Raya VM
PEM starts with: -----BEGIN CERTIFICATE-----
chain accepted from bytes
void setClientAuthorities(String file, {String? password})

Sets the list of authority names that a SecureServerSocket will advertise as accepted when requesting a client certificate from a connecting client.

The file is a PEM or PKCS12 file containing the accepted signing authority certificates - the authority names are extracted from the certificates. For PKCS12 files, password is the password for the file. For PEM files, password is ignored. Assuming it is well-formatted, all other contents of file are ignored.

NB: This function calls File.readAsBytesSync, and will block on file IO. Prefer using setClientAuthoritiesBytes.

iOS note: This call is not supported.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  // Tell clients which CAs may sign the certificates they present.
  ctx.setClientAuthorities('${d.path}/c.pem');
  final server = await SecureServerSocket.bind(InternetAddress.loopbackIPv4, 0, ctx, requestClientCertificate: true);
  print('server will ask clients for a certificate signed by our CA');
  await server.close();
  d.deleteSync(recursive: true);
}
Output from the Raya VM
server will ask clients for a certificate signed by our CA
void setClientAuthoritiesBytes(List<int> authCertBytes, {String? password})

Sets the list of authority names that a SecureServerSocket will advertise as accepted, when requesting a client certificate from a connecting client.

Like setClientAuthorities but takes the contents of the file.

Example
import 'raya:io';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final ctx = (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem'));
  ctx.setClientAuthoritiesBytes(File('${d.path}/c.pem').readAsBytesSync());
  print('client authorities loaded from bytes');
  d.deleteSync(recursive: true);
}
Output from the Raya VM
client authorities loaded from bytes
void setAlpnProtocols(List<String> protocols, bool isServer)

Sets the list of application-level protocols supported by a client connection or server connection. The ALPN (application level protocol negotiation) extension to TLS allows a client to send a list of protocols in the TLS client hello message, and the server to pick one and send the selected one back in its server hello message.

Separate lists of protocols can be sent for client connections and for server connections, using the same SecurityContext. The isServer boolean argument specifies whether to set the list for server connections or client connections.

Example
import 'raya:io';

void main() {
  final ctx = SecurityContext();
  ctx.setAlpnProtocols(['h2', 'http/1.1'], false);
  print('client ALPN list set: h2, http/1.1');
  try {
    ctx.setAlpnProtocols(['x' * 300], false);
  } on ArgumentError {
    print('a protocol name over 255 bytes: ArgumentError');
  }
}
Output from the Raya VM
client ALPN list set: h2, http/1.1
a protocol name over 255 bytes: ArgumentError
final class InternetAddressType

The type, or address family, of an InternetAddress.

Currently, IP version 4 (IPv4), IP version 6 (IPv6) and Unix domain address are supported. Unix domain sockets are available only on Linux, MacOS and Android.

Static

IPv4constant
static const InternetAddressType IPv4 = InternetAddressType._(0)
IPv6constant
static const InternetAddressType IPv6 = InternetAddressType._(1)
unixconstant
static const InternetAddressType unix = InternetAddressType._(2)
anyconstant
static const InternetAddressType any = InternetAddressType._(-1)

Properties

namegetter
String get name

Get the name of the type, e.g. "IPv4" or "IPv6".

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(InternetAddressType.IPv4);
  print(InternetAddressType.IPv6);
  print(InternetAddressType.unix);
}
Output
InternetAddressType: IPv4
InternetAddressType: IPv6
InternetAddressType: Unix
abstract interface class InternetAddress

An internet address or a Unix domain address.

This object holds an internet address. If this internet address is the result of a DNS lookup, the address also holds the hostname used to make the lookup. An Internet address combined with a port number represents an endpoint to which a socket can connect or a listening socket can bind.

Constructors

external factory InternetAddress(String address, {InternetAddressType? type})

Creates a new InternetAddress from a numeric address or a file path.

If type is InternetAddressType.IPv4, address must be a numeric IPv4 address (dotted-decimal notation). If type is InternetAddressType.IPv6, address must be a numeric IPv6 address (hexadecimal notation). If type is InternetAddressType.unix, address must be a valid file path. If type is omitted, address must be either a numeric IPv4 or IPv6 address and the type is inferred from the format.

Example
import 'raya:io';

void main() {
  final v4 = InternetAddress('192.168.0.10');
  final v6 = InternetAddress('::1');
  print('${v4.address}: ${v4.type}, loopback ${v4.isLoopback}');
  print('${v6.address}: ${v6.type}, loopback ${v6.isLoopback}');
  print('raw bytes: ${v4.rawAddress}');
}
Output from the Raya VM
192.168.0.10: InternetAddressType: IPv4, loopback false
::1: InternetAddressType: IPv6, loopback true
raw bytes: [192, 168, 0, 10]
external factory InternetAddress.fromRawAddress(Uint8List rawAddress, {InternetAddressType? type})

Creates a new InternetAddress from the provided raw address bytes.

If the type is InternetAddressType.IPv4, the rawAddress must have length 4. If the type is InternetAddressType.IPv6, the rawAddress must have length 16. If the type is InternetAddressType.unix, the rawAddress must be a valid UTF-8 encoded file path.

If type is omitted, the rawAddress must have a length of either 4 or 16, in which case the type defaults to InternetAddressType.IPv4 or InternetAddressType.IPv6 respectively.

Example
import 'raya:io';
import 'raya:typed_data';

void main() {
  final a = InternetAddress.fromRawAddress(Uint8List.fromList([10, 0, 0, 1]));
  print('${a.address} (${a.type})');
  final b = InternetAddress.fromRawAddress(Uint8List(16)..[15] = 1);
  print('${b.address} is loopback: ${b.isLoopback}');
}
Output from the Raya VM
10.0.0.1 (InternetAddressType: IPv4)
::1 is loopback: true

Static

loopbackIPv4staticgetter
external static InternetAddress get loopbackIPv4

IP version 4 loopback address.

Use this address when listening on or connecting to the loopback adapter using IP version 4 (IPv4).

loopbackIPv6staticgetter
external static InternetAddress get loopbackIPv6

IP version 6 loopback address.

Use this address when listening on or connecting to the loopback adapter using IP version 6 (IPv6).

anyIPv4staticgetter
external static InternetAddress get anyIPv4

IP version 4 any address.

Use this address when listening on the addresses of all adapters using IP version 4 (IPv4).

anyIPv6staticgetter
external static InternetAddress get anyIPv6

IP version 6 any address.

Use this address when listening on the addresses of all adapters using IP version 6 (IPv6).

lookupstaticmethod
external static Future<List<InternetAddress>> lookup(String host, {InternetAddressType type = InternetAddressType.any})

Looks up the addresses of a host.

If type is InternetAddressType.any, it will lookup both IP version 4 (IPv4) and IP version 6 (IPv6) addresses. If type is either InternetAddressType.IPv4 or InternetAddressType.IPv6 it will only lookup addresses of the specified type. The order of the list can, and most likely will, change over time.

Example
import 'raya:io';

Future<void> main() async {
  final found = await InternetAddress.lookup('localhost', type: InternetAddressType.IPv4);
  print('localhost (IPv4): ${found.map((a) => a.address).toSet()}');
  print('all loopback: ${found.every((a) => a.isLoopback)}');
}
Output from the Raya VM
localhost (IPv4): {127.0.0.1}
all loopback: true
tryParsestaticmethod
external static InternetAddress? tryParse(String address)

Attempts to parse address as a numeric address.

Returns null If address is not a numeric IPv4 (dotted-decimal notation) or IPv6 (hexadecimal representation) address.

Example
import 'raya:io';

void main() {
  for (final s in ['127.0.0.1', 'fe80::1', '300.1.2.3', 'example.com']) {
    print('$s -> ${InternetAddress.tryParse(s)?.type}');
  }
}
Output from the Raya VM
127.0.0.1 -> InternetAddressType: IPv4
fe80::1 -> InternetAddressType: IPv6
300.1.2.3 -> null
example.com -> null

Properties

typegetter
InternetAddressType get type

The address family of the InternetAddress.

addressgetter
String get address

The numeric address of the host.

For IPv4 addresses this is using the dotted-decimal notation. For IPv6 it is using the hexadecimal representation. For Unix domain addresses, this is a file path.

hostgetter
String get host

The host used to lookup the address.

If there is no host associated with the address this returns the address.

Uint8List get rawAddress

The raw address of this InternetAddress.

For an IP address, the result is either a 4 or 16 byte long list. For a Unix domain address, UTF-8 encoded byte sequences that represents address is returned.

The returned list is a fresh copy, making it possible to change the list without modifying the InternetAddress.

bool get isLoopback

Whether the InternetAddress is a loopback address.

bool get isLinkLocal

Whether the scope of the InternetAddress is a link-local.

bool get isMulticast

Whether the scope of the InternetAddress is multicast.

Methods

reversemethod
Future<InternetAddress> reverse()

Performs a reverse DNS lookup on this address

Returns a new InternetAddress with the same address, but where the host field set to the result of the lookup.

If this address is Unix domain addresses, no lookup is performed and this address is returned directly.

Example
import 'raya:io';

Future<void> main() async {
  final a = await InternetAddress('127.0.0.1').reverse();
  print('127.0.0.1 reverse lookup: ${a.host}');
}
Output from the Raya VM
127.0.0.1 reverse lookup: localhost
abstract interface class InterfaceAddress implements InternetAddress

An InternetAddress bound to a NetworkInterface, extended with network configuration details.

In addition to the address itself, provides the prefix length (also known as subnet mask length) and, for IPv4 addresses, the broadcast address of the network.

Properties

int get prefixLength

The prefix length of the network, also known as the subnet mask length.

For example, a prefix length of 24 corresponds to a subnet mask of 255.255.255.0 in IPv4. For IPv6, a prefix length of 64 means the first 64 bits of the address are the network prefix.

broadcastgetter
InternetAddress? get broadcast

The broadcast address of this network.

Only IPv4 networks have broadcast addresses. Returns null for IPv6 addresses.

abstract interface class NetworkInterface

A NetworkInterface represents an active network interface on the current system. It contains a list of InterfaceAddresses that are bound to the interface.

Static

listSupportedstaticgetterdeprecated
external static bool get listSupported

Whether the list method is supported.

The list method is supported on all platforms supported by Raya so this property is always true.

liststaticmethod
external static Future<List<NetworkInterface>> list({bool includeLoopback = false, bool includeLinkLocal = false, InternetAddressType type = InternetAddressType.any})

Query the system for NetworkInterfaces.

If includeLoopback is true, the returned list will include the loopback device. Default is false.

If includeLinkLocal is true, the list of addresses of the returned NetworkInterfaces, may include link local addresses. Default is false.

If type is either InternetAddressType.IPv4 or InternetAddressType.IPv6 it will only lookup addresses of the specified type. Default is InternetAddressType.any.

Example
import 'raya:io';

Future<void> main() async {
  final all = await NetworkInterface.list(includeLoopback: true, type: InternetAddressType.IPv4);
  final hasLoopback = all.any((i) => i.addresses.any((a) => a.address == '127.0.0.1'));
  print('an interface carries 127.0.0.1: $hasLoopback');
}
Output from the Raya VM
an interface carries 127.0.0.1: true

Properties

namegetter
String get name

The name of the NetworkInterface.

indexgetter
int get index

The index of the NetworkInterface.

addressesgetter
List<InterfaceAddress> get addresses

The list of InterfaceAddresses currently bound to this NetworkInterface.

abstract interface class RawServerSocket implements Stream<RawSocket>

A listening socket.

A RawServerSocket and provides a stream of low-level RawSocket objects, one for each connection made to the listening socket.

See RawSocket for more information.

Static

bindstaticmethod
external static Future<RawServerSocket> bind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false})

Listens on a given address and port.

When the returned future completes the server socket is bound to the given address and port and has started listening on it.

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only.

If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

The optional argument shared specifies whether additional RawServerSocket objects can bind to the same combination of address, port and v6Only. If shared is true and more RawServerSockets from this isolate or other isolates are bound to the port, then the incoming connections will be distributed among all the bound RawServerSockets. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await RawServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((RawSocket conn) {
    conn.write([1, 2, 3]);
    conn.close();
  });
  final client = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  print('client received: ${await client.expand((c) => c).toList().timeout(t)}');
  client.destroy();
  await server.close();
}
Output from the Raya VM
client received: [1, 2, 3]

Properties

portgetter
int get port

The port used by this socket.

addressgetter
InternetAddress get address

The address used by this socket.

Methods

closemethod
Future<RawServerSocket> close()

Closes the socket.

The returned future completes when the socket is fully closed and is no longer bound.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await RawServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  var accepted = 0;
  final done = server.listen((c) {
    accepted++;
    c.close();
  }).asFuture<void>();
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  await s.drain<void>().timeout(t);
  s.destroy();
  await server.close();
  await done.timeout(t);
  print('server stream done; accepted $accepted');
}
Output from the Raya VM
server stream done; accepted 1
abstract interface class ServerSocket implements ServerSocketBase<Socket>

A listening socket.

A ServerSocket provides a stream of Socket objects, one for each connection made to the listening socket.

See Socket for more info.

Static

bindstaticmethod
static Future<ServerSocket> bind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false})

Listens on a given address and port.

When the returned future completes the server socket is bound to the given address and port and has started listening on it.

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only.

If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

The optional argument shared specifies whether additional ServerSocket objects can bind to the same combination of address, port and v6Only. If shared is true and more server sockets from this isolate or other isolates are bound to the port, then the incoming connections will be distributed among all the bound server sockets. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); // port 0: pick a free port
  server.listen((client) {
    client.listen((data) {
      client.write('echo: ${utf8.decode(data)}');
      client.close();
    });
  });
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  s.write('ping');
  print(await utf8.decoder.bind(s).join().timeout(t));
  s.destroy();
  await server.close();
}
Output from the Raya VM
echo: ping

Properties

portgetter
int get port

The port used by this socket.

addressgetter
InternetAddress get address

The address used by this socket.

Methods

closemethod
Future<ServerSocket> close()

Closes the socket.

The returned future completes when the socket is fully closed and is no longer bound.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final port = server.port;
  final done = server.drain<void>();
  await server.close();
  await done;
  print('listen stream finished after close');
  try {
    await Socket.connect(InternetAddress.loopbackIPv4, port).timeout(const Duration(seconds: 2));
  } on SocketException {
    print('new connections are refused');
  }
}
Output from the Raya VM
listen stream finished after close
new connections are refused
final class SocketDirection

The SocketDirection is used as a parameter to Socket.close and RawSocket.close to close a socket in the specified direction(s).

Static

receiveconstant
static const SocketDirection receive = SocketDirection._(0)
sendconstant
static const SocketDirection send = SocketDirection._(1)
bothconstant
static const SocketDirection both = SocketDirection._(2)
final class SocketOption

An option for a socket which is configured using Socket.setOption.

The SocketOption is used as a parameter to Socket.setOption and RawSocket.setOption to customize the behaviour of the underlying socket.

Static

tcpNoDelayconstant
static const SocketOption tcpNoDelay = SocketOption._(0)

Enable or disable no-delay on the socket. If tcpNoDelay is enabled, the socket will not buffer data internally, but instead write each data chunk as an individual TCP packet.

tcpNoDelay is disabled by default.

final class RawSocketOption

The RawSocketOption is used as a parameter to Socket.setRawOption and RawSocket.setRawOption to customize the behaviour of the underlying socket.

It allows for fine grained control of the socket options, and its values will be passed to the underlying platform's implementation of setsockopt and getsockopt.

Constructors

RawSocketOptionconstructor
const RawSocketOption(this.level, this.option, this.value)

Creates a RawSocketOption for RawSocket.getRawOption and RawSocket.setRawOption.

The level and option arguments correspond to level and optname arguments on the getsockopt and setsockopt native calls.

The value argument and its length correspond to the optval and length arguments on the native call.

For a RawSocket.getRawOption call, the value parameter will be updated after a successful call (although its length will not be changed).

For a RawSocket.setRawOption call, the value parameter will be used set the option.

Example
import 'raya:io';
import 'raya:typed_data';

void main() {
  // TCP_NODELAY is option 1 at the TCP level on macOS and Linux.
  final opt = RawSocketOption(RawSocketOption.levelTcp, 1, Uint8List.fromList([1, 0, 0, 0]));
  print('level ${opt.level == RawSocketOption.levelTcp ? 'TCP' : opt.level}, option ${opt.option}, value ${opt.value}');
}
Output from the Raya VM
level TCP, option 1, value [1, 0, 0, 0]
factory RawSocketOption.fromInt(int level, int option, int value)

Convenience constructor for creating an integer based RawSocketOption.

Example
import 'raya:io';

void main() {
  final opt = RawSocketOption.fromInt(RawSocketOption.levelSocket, 0x1001, 65536);
  print('value bytes (native order): ${opt.value}');
}
Output from the Raya VM
value bytes (native order): [0, 0, 1, 0]
factory RawSocketOption.fromBool(int level, int option, bool value)

Convenience constructor for creating a boolean based RawSocketOption.

Example
import 'raya:io';

void main() {
  final on = RawSocketOption.fromBool(RawSocketOption.levelTcp, 1, true);
  final off = RawSocketOption.fromBool(RawSocketOption.levelTcp, 1, false);
  print('true -> ${on.value}, false -> ${off.value}');
}
Output from the Raya VM
true -> [1, 0, 0, 0], false -> [0, 0, 0, 0]

Static

levelSocketstaticgetter
static int get levelSocket

Socket level option for SOL_SOCKET.

levelIPv4staticgetter
static int get levelIPv4

Socket level option for IPPROTO_IP.

static int get IPv4MulticastInterface

Socket option for IP_MULTICAST_IF.

levelIPv6staticgetter
static int get levelIPv6

Socket level option for IPPROTO_IPV6.

static int get IPv6MulticastInterface

Socket option for IPV6_MULTICAST_IF.

levelTcpstaticgetter
static int get levelTcp

Socket level option for IPPROTO_TCP.

levelUdpstaticgetter
static int get levelUdp

Socket level option for IPPROTO_UDP.

Properties

optionfield
final int option

The numeric ID of the option to set or get.

valuefield
final Uint8List value

The raw data to set, or the array to write the current option value into.

This list must be the correct length for the expected option. For most options that take int or bool values, the length should be 4. For options that expect a struct (such as an in_addr_t), the length should be the correct length for that struct.

class RawSocketEvent

Events for the RawDatagramSocket, RawSecureSocket, and RawSocket.

These event objects are used by the Stream behavior of the sockets (for example RawSocket.listen, RawSocket.forEach) when the socket's state change.

import 'raya:convert';
import 'raya:io';

void main() async {
  final socket = await RawSocket.connect("example.com", 80);

  socket.listen((event) {
    switch (event) {
      case RawSocketEvent.read:
        final data = socket.read();
        if (data != null) {
          print(ascii.decode(data));
        }
        break;
      case RawSocketEvent.write:
        socket.write(ascii.encode('GET /\r\nHost: example.com\r\n\r\n'));
        socket.writeEventsEnabled = false;
        break;
      case RawSocketEvent.readClosed:
        socket.close();
        break;
      case RawSocketEvent.closed:
        break;
      default:
        throw "Unexpected event $event";
    }
  });
}

Static

readconstant
static const RawSocketEvent read = RawSocketEvent._(0)

An event indicates the socket is ready to be read.

writeconstant
static const RawSocketEvent write = RawSocketEvent._(1)

An event indicates the socket is ready to write.

readClosedconstant
static const RawSocketEvent readClosed = RawSocketEvent._(2)

An event indicates the reading from the socket is closed

closedconstant
static const RawSocketEvent closed = RawSocketEvent._(3)

An event indicates the socket is closed.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  for (final e in [RawSocketEvent.read, RawSocketEvent.write, RawSocketEvent.readClosed, RawSocketEvent.closed]) {
    print(e);
  }
}
Output
RawSocketEvent.read
RawSocketEvent.write
RawSocketEvent.readClosed
RawSocketEvent.closed
final class ConnectionTask<S>

A cancelable connection attempt.

Returned by the startConnect methods on client-side socket types S, ConnectionTask<S> allows canceling an attempt to connect to a host.

Static

fromSocketstaticmethod
static ConnectionTask<T> fromSocket<T extends Socket>(Future<T> socket, void Function() onCancel)

Create a ConnectionTask from an existing Future<Socket>.

You can use this method to return existing socket connections in HttpClient.connectionFactory.

For example:

final clientSocketFuture = Socket.connect(
    serverUri.host, serverUri.port);
final client = HttpClient()
 ..connectionFactory = (uri, proxyHost, proxyPort) {
   return Future.value(
       ConnectionTask.fromSocket(clientSocketFuture, () {}));
final response = await client.getUrl(serverUri);
Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  // Wrap any Future<Socket> so it can be cancelled like Socket.startConnect.
  final task = ConnectionTask.fromSocket(Socket.connect(InternetAddress.loopbackIPv4, server.port), () => print('cancelled'));
  final socket = await task.socket.timeout(const Duration(seconds: 2));
  print('connected to port ${socket.remotePort == server.port}');
  socket.destroy();
  await server.close();
}
Output from the Raya VM
connected to port true

Properties

socketfield
final Future<S> socket

A Future that completes with value that S.connect would return unless cancel is called on this ConnectionTask.

If cancel is called, the future completes with a SocketException error whose message indicates that the connection attempt was cancelled.

Methods

cancelmethod
void cancel()

Cancels the connection attempt.

This also causes the socket Future to complete with a SocketException error.

Example
import 'raya:io';

Future<void> main() async {
  // 10.255.255.1 is unroutable, so the connection would hang; cancel it.
  final task = await Socket.startConnect('10.255.255.1', 9);
  task.cancel();
  try {
    await task.socket.timeout(const Duration(seconds: 2));
  } on SocketException catch (e) {
    print('after cancel: ${e.message}');
  }
}
Output from the Raya VM
after cancel: Connection attempt cancelled, host: InternetAddress('10.255.255.1', IPv4), port: 9
abstract interface class RawSocket implements Stream<RawSocketEvent>

A TCP connection.

A socket connection connects a local socket to a remote socket. Data, as Uint8Lists, is received by the local socket and made available by the read method, and can be sent to the remote socket through the write method.

The Stream interface of this class provides event notification about when a certain change has happened, for example when data has become available (RawSocketEvent.read) or when the remote end has stopped listening (RawSocketEvent.closed).

Static

connectstaticmethod
external static Future<RawSocket> connect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout})

Creates a new socket connection to the host and port.

Returns a Future that will complete with either a RawSocket once connected, or an error if the host-lookup or connection failed.

The host can either be a String or an InternetAddress. If host is a String, connect will perform a InternetAddress.lookup and try all returned InternetAddresses, until connected. If IPv4 and IPv6 addresses are both available then connections over IPv4 are preferred. If no connection can be established then the error from the first failing connection is returned.

The argument sourceAddress can be used to specify the local address to bind when making the connection. The sourceAddress can either be a String or an InternetAddress. If a String is passed it must hold a numeric IP address.

The sourcePort defines the local port to bind to. If sourcePort is not specified or zero, a port will be chosen.

The argument timeout is used to specify the maximum allowed time to wait for a connection to be established. If timeout is longer than the system level timeout duration, a timeout may occur sooner than specified in timeout. On timeout, a SocketException is thrown and all ongoing connection attempts to host are cancelled.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s..add([42])..close()..drain<void>());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  await for (final event in raw.timeout(t)) {
    if (event == RawSocketEvent.read) print('read: ${raw.read()}');
    if (event == RawSocketEvent.readClosed) break;
  }
  await raw.close();
  await server.close();
}
Output from the Raya VM
read: [42]
startConnectstaticmethod
external static Future<ConnectionTask<RawSocket>> startConnect(host, int port, {sourceAddress, int sourcePort = 0})

Like connect, but returns a Future that completes with a ConnectionTask that can be cancelled if the RawSocket is no longer needed.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final task = await RawSocket.startConnect(InternetAddress.loopbackIPv4, server.port);
  final raw = await task.socket.timeout(const Duration(seconds: 2));
  print('connected: ${raw.remotePort == server.port}');
  await raw.close();
  await server.close();
}
Output from the Raya VM
connected: true

Properties

abstract bool readEventsEnabled

Set or get, if the RawSocket should listen for RawSocketEvent.read and RawSocketEvent.readClosed events. Default is true.

Warning: setting readEventsEnabled to false might prevent socket from fully closing when SocketDirection.receive and SocketDirection.send directions are shutdown independently. See shutdown for more details.

abstract bool writeEventsEnabled

Set or get, if the RawSocket should listen for RawSocketEvent.write events. Default is true. This is a one-shot listener, and writeEventsEnabled must be set to true again to receive another write event.

portgetter
int get port

The port used by this socket.

Throws a SocketException if the socket is closed.

int get remotePort

The remote port connected to by this socket.

Throws a SocketException if the socket is closed.

addressgetter
InternetAddress get address

The InternetAddress used to connect this socket.

Throws a SocketException if the socket is closed.

InternetAddress get remoteAddress

The remote InternetAddress connected to by this socket.

Throws a SocketException if the socket is closed.

Methods

availablemethod
int available()

The number of received and non-read bytes in the socket that can be read.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s..add(List.filled(10, 1))..close()..drain<void>());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  var total = 0;
  await for (final e in raw.timeout(t)) {
    if (e == RawSocketEvent.read) total += raw.read(raw.available())!.length;
    if (e == RawSocketEvent.readClosed) break;
  }
  print('read $total bytes, asking available() each time');
  await raw.close();
  await server.close();
}
Output from the Raya VM
read 10 bytes, asking available() each time
readmethod
Uint8List? read([int? len])

Read up to len bytes from the socket.

This function is non-blocking and will only return data if data is available. The number of bytes read can be less than len if fewer bytes are available for immediate reading. If no data is available null is returned.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s..add([1, 2, 3, 4, 5, 6])..close()..drain<void>());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  final got = <int>[];
  await for (final e in raw.timeout(t)) {
    if (e == RawSocketEvent.read) {
      for (List<int>? c; (c = raw.read(2)) != null;) got.addAll(c!); // at most 2 bytes per call
    }
    if (e == RawSocketEvent.readClosed) break;
  }
  print('bytes: $got');
  await raw.close();
  await server.close();
}
Output from the Raya VM
bytes: [1, 2, 3, 4, 5, 6]
SocketMessage? readMessage([int? count])

Reads a message containing up to count bytes from the socket.

This function differs from read in that it will also return any SocketControlMessage that have been sent.

This function is non-blocking and will only return data if data is available. The number of bytes read can be less than count if fewer bytes are available for immediate reading. Length of data buffer in SocketMessage indicates number of bytes read.

Returns null if no data is available.

Unsupported by RawSecureSocket.

Unsupported on Android, Fuchsia, Windows.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final addr = InternetAddress('${tmp.path}/s', type: InternetAddressType.unix);
  final server = await RawServerSocket.bind(addr, 0);
  final client = await RawSocket.connect(addr, 0).timeout(t);
  final peer = await server.first.timeout(t);
  client.sendMessage([], [10, 20, 30]);
  await for (final e in peer.timeout(t)) {
    final m = e == RawSocketEvent.read ? peer.readMessage() : null;
    if (m != null) {
      print('data ${m.data}, control messages ${m.controlMessages.length}');
      break;
    }
  }
  await client.close();
  await peer.close();
  await server.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
data [10, 20, 30], control messages 0
writemethod
int write(List<int> buffer, [int offset = 0, int? count])

Writes up to count bytes of the buffer from offset buffer offset to the socket.

The number of successfully written bytes is returned. This function is non-blocking and will only write data if buffer space is available in the socket. This means that the number of successfully written bytes may be less than count or even 0.

Transmission of the buffer may be delayed unless SocketOption.tcpNoDelay is set with RawSocket.setOption.

The default value for offset is 0, and the default value for count is buffer.length - offset.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final received = server.first.then((s) async {
    final text = await utf8.decoder.bind(s).join();
    s.destroy();
    return text;
  });
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  final n = raw.write(utf8.encode('xxhello'), 2); // skip the first two bytes
  print('write returned $n');
  await raw.close();
  print('server got: ${await received.timeout(t)}');
  await server.close();
}
Output from the Raya VM
write returned 5
server got: hello
int sendMessage(List<SocketControlMessage> controlMessages, List<int> data, [int offset = 0, int? count])

Writes socket control messages and data bytes to the socket.

Writes controlMessages and up to count bytes of data, starting at offset, to the socket. If count is not provided, as many bytes as possible are written. Use write instead if no control messages are required to be sent.

When sent control messages are received, they are retained until the next call to readMessage, where all currently available control messages are provided as part of the returned SocketMessage. Calling read will read only data bytes, and will not affect control messages.

The count must be positive (greater than zero).

Returns the number of bytes written, which cannot be greater than count, nor greater than data.length - offset. Return value of zero indicates that control messages were not sent.

This function is non-blocking and will only write data if buffer space is available in the socket.

Throws an OSError if message could not be sent out.

Unsupported by RawSecureSocket.

Unsupported on Android, Fuchsia, Windows.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final addr = InternetAddress('${tmp.path}/s', type: InternetAddressType.unix);
  final server = await RawServerSocket.bind(addr, 0);
  final client = await RawSocket.connect(addr, 0).timeout(t);
  final peer = await server.first.timeout(t);
  final f = File('${tmp.path}/x')..writeAsStringSync('x');
  final fd = SocketControlMessage.fromHandles([ResourceHandle.fromFile(f.openSync())]);
  print('sent ${client.sendMessage([fd], [1, 2, 3, 4], 1)} data bytes plus one file descriptor');
  await for (final e in peer.timeout(t)) {
    final m = e == RawSocketEvent.read ? peer.readMessage() : null;
    if (m != null) {
      print('peer data: ${m.data}, handles: ${m.controlMessages.single.extractHandles().length}');
      break;
    }
  }
  await client.close();
  await peer.close();
  await server.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
sent 3 data bytes plus one file descriptor
peer data: [2, 3, 4], handles: 1
closemethod
Future<RawSocket> close()

Closes the socket.

Returns a future that completes with this socket when the underlying connection is completely destroyed.

Calling close will never throw an exception and calling it several times is supported. Calling close can result in a RawSocketEvent.readClosed event.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final serverSide = server.first;
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  await raw.close();
  final s = await serverSide.timeout(t);
  print('server sees end of stream, bytes: ${(await s.toList().timeout(t)).length}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
server sees end of stream, bytes: 0
shutdownmethod
void shutdown(SocketDirection direction)

Shuts down the socket in the direction.

Calling shutdown will never throw an exception and calling it several times is supported. Calling shutdown with either SocketDirection.both or SocketDirection.receive can result in a RawSocketEvent.readClosed event.

Warning: SocketDirection.receive direction is only considered to be to be fully shutdown once all available data is drained and RawSocketEvent.readClosed is dispatched. Shutting down SocketDirection.receive and SocketDirection.send directions separately without draining the data will lead to socket staying around until the data is drained. This can happen if readEventsEnabled is set to false or if received data is not read in response to these events. This does not apply to shutting down both directions simultaneously using SocketDirection.both which will discard all received data instead.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) async {
    final msg = await utf8.decoder.bind(s).join(); // ends when the client shuts down sending
    s.write('got "$msg"');
    await s.close();
  });
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  raw.write(utf8.encode('request'));
  raw.shutdown(SocketDirection.send);
  final reply = <int>[];
  await for (final e in raw) {
    if (e == RawSocketEvent.read) reply.addAll(raw.read()!);
    if (e == RawSocketEvent.readClosed) raw.close();
  }
  print('reply after half-close: ${utf8.decode(reply)}');
  await server.close();
}
Output from the Raya VM
reply after half-close: got "request"
setOptionmethod
bool setOption(SocketOption option, bool enabled)

Customize the RawSocket.

See SocketOption for available options.

Returns true if the option was set successfully, false otherwise.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  print('tcpNoDelay set: ${raw.setOption(SocketOption.tcpNoDelay, true)}');
  await raw.close();
  await server.close();
}
Output from the Raya VM
tcpNoDelay set: true
Uint8List getRawOption(RawSocketOption option)

Reads low level information about the RawSocket.

See RawSocketOption for available options.

Returns the RawSocketOption.value on success.

Throws an OSError on failure.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  raw.setOption(SocketOption.tcpNoDelay, true);
  final v = raw.getRawOption(RawSocketOption.fromInt(RawSocketOption.levelTcp, 1, 0)); // TCP_NODELAY
  print('TCP_NODELAY is on: ${v.any((b) => b != 0)}');
  await raw.close();
  await server.close();
}
Output from the Raya VM
TCP_NODELAY is on: true
void setRawOption(RawSocketOption option)

Customizes the RawSocket.

See RawSocketOption for available options.

Throws an OSError on failure.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  raw.setRawOption(RawSocketOption.fromBool(RawSocketOption.levelTcp, 1, true)); // TCP_NODELAY
  final v = raw.getRawOption(RawSocketOption.fromInt(RawSocketOption.levelTcp, 1, 0));
  print('read back: ${v.any((b) => b != 0)}');
  await raw.close();
  await server.close();
}
Output from the Raya VM
read back: true
class

Socket

abstract interface class Socket implements Stream<Uint8List>, IOSink

A TCP connection between two sockets.

A socket connection connects a local socket to a remote socket. Data, as Uint8Lists, is received by the local socket, made available by the Stream interface of this class, and can be sent to the remote socket through the IOSink interface of this class.

Transmission of the data sent through the IOSink interface may be delayed unless SocketOption.tcpNoDelay is set with Socket.setOption.

Static

connectstaticmethod
static Future<Socket> connect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout})

Creates a new socket connection to the host and port and returns a Future that will complete with either a Socket once connected or an error if the host-lookup or connection failed.

host can either be a String or an InternetAddress. If host is a String, connect will perform a InternetAddress.lookup and try all returned InternetAddresses, until connected. Unless a connection was established, the error from the first failing connection is returned.

The argument sourceAddress can be used to specify the local address to bind when making the connection. The sourceAddress can either be a String or an InternetAddress. If a String is passed it must hold a numeric IP address.

The sourcePort defines the local port to bind to. If sourcePort is not specified or zero, a port will be chosen.

The argument timeout is used to specify the maximum allowed time to wait for a connection to be established. If timeout is longer than the system level timeout duration, a timeout may occur sooner than specified in timeout. On timeout, a SocketException is thrown and all ongoing connection attempts to host are cancelled.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((c) => c..write('HELLO')..close()..drain<void>());
  final s = await Socket.connect('127.0.0.1', server.port, timeout: t);
  print('remote is loopback: ${s.remoteAddress.isLoopback}');
  print('received: ${await utf8.decoder.bind(s).join().timeout(t)}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
remote is loopback: true
received: HELLO
startConnectstaticmethod
static Future<ConnectionTask<Socket>> startConnect(host, int port, {sourceAddress, int sourcePort = 0})

Like connect, but returns a Future that completes with a ConnectionTask that can be cancelled if the Socket is no longer needed.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((c) => c..add([7])..close()..drain<void>());
  final task = await Socket.startConnect(InternetAddress.loopbackIPv4, server.port);
  final s = await task.socket.timeout(t);
  print('received: ${await s.expand((c) => c).toList().timeout(t)}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
received: [7]

Properties

portgetter
int get port

The port used by this socket.

Throws a SocketException if the socket is closed. The port is 0 if the socket is a Unix domain socket.

int get remotePort

The remote port connected to by this socket.

Throws a SocketException if the socket is closed. The port is 0 if the socket is a Unix domain socket.

addressgetter
InternetAddress get address

The InternetAddress used to connect this socket.

Throws a SocketException if the socket is closed.

InternetAddress get remoteAddress

The remote InternetAddress connected to by this socket.

Throws a SocketException if the socket is closed.

donegetter
Future get done

Methods

destroymethod
void destroy()

Destroys the socket in both directions.

Calling destroy will make the send a close event on the stream and will no longer react on data being piped to it.

Call close (inherited from IOSink) to only close the Socket for sending data.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final serverSide = server.first;
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  s.destroy(); // closes both directions at once, dropping unsent data
  final peer = await serverSide.timeout(t);
  print('peer stream ended, bytes: ${(await peer.toList().timeout(t)).length}');
  peer.destroy();
  await server.close();
}
Output from the Raya VM
peer stream ended, bytes: 0
setOptionmethod
bool setOption(SocketOption option, bool enabled)

Customizes the RawSocket.

See SocketOption for available options.

Returns true if the option was set successfully, false otherwise.

Throws a SocketException if the socket has been destroyed or upgraded to a secure socket.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  // Send small writes immediately instead of batching them.
  print('tcpNoDelay: ${s.setOption(SocketOption.tcpNoDelay, true)}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
tcpNoDelay: true
Uint8List getRawOption(RawSocketOption option)

Reads low level information about the RawSocket.

See RawSocketOption for available options.

Returns the RawSocketOption.value on success.

Throws an OSError on failure and a SocketException if the socket has been destroyed or upgraded to a secure socket.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  final before = s.getRawOption(RawSocketOption.fromInt(RawSocketOption.levelTcp, 1, 0));
  s.setOption(SocketOption.tcpNoDelay, true);
  final after = s.getRawOption(RawSocketOption.fromInt(RawSocketOption.levelTcp, 1, 0));
  print('TCP_NODELAY before: ${before.any((b) => b != 0)}, after: ${after.any((b) => b != 0)}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
TCP_NODELAY before: false, after: true
void setRawOption(RawSocketOption option)

Customizes the RawSocket.

See RawSocketOption for available options.

Throws an OSError on failure and a SocketException if the socket has been destroyed or upgraded to a secure socket.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.destroy());
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(const Duration(seconds: 2));
  s.setRawOption(RawSocketOption.fromBool(RawSocketOption.levelTcp, 1, true));
  print('set TCP_NODELAY through a raw option');
  s.destroy();
  await server.close();
}
Output from the Raya VM
set TCP_NODELAY through a raw option
addErrormethod
void addError(Object error, [StackTrace? stackTrace])

Unsupported operation on sockets.

This method, which is inherited from IOSink, is not supported on sockets, and must not be called. Sockets have no way to report errors, so any error passed in to a socket using addError would be lost.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((s) => s.drain<void>().whenComplete(s.destroy));
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  try {
    s.addError(StateError('cannot be sent'));
    print('addError accepted');
  } on UnsupportedError {
    print('sockets cannot carry errors: UnsupportedError');
  }
  s.destroy();
  await server.close();
}
Output from the Raya VM
sockets cannot carry errors: UnsupportedError
closemethod
Future close()
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final got = server.first.then((c) => utf8.decoder.bind(c).join().whenComplete(c.destroy));
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  s.write('all of this is sent before closing');
  await s.close(); // flushes, then closes the sending side
  print('server read: ${await got.timeout(t)}');
  s.destroy();
  await server.close();
}
Output from the Raya VM
server read: all of this is sent before closing
final class Datagram

A data packet received by a RawDatagramSocket.

Constructors

Datagramconstructor
Datagram(this.data, this.address, this.port)
Example
import 'raya:io';
import 'raya:typed_data';

void main() {
  final d = Datagram(Uint8List.fromList([1, 2, 3]), InternetAddress.loopbackIPv4, 9000);
  print('${d.data.length} bytes from ${d.address.address}:${d.port}');
}
Output from the Raya VM
3 bytes from 127.0.0.1:9000

Properties

datafield
Uint8List data

The actual bytes of the message.

addressfield
InternetAddress address

The address of the socket which sends the data.

portfield
int port

The port of the socket which sends the data.

abstract interface class ResourceHandle

A wrapper around OS resource handle so it can be passed via Socket as part of SocketMessage.

Constructors

external factory ResourceHandle.fromFile(RandomAccessFile file)

Creates wrapper around opened file.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = (File('${tmp.path}/a.txt')..writeAsStringSync('shared file')).openSync();
  // A handle wraps the OS file descriptor so it can travel in a socket control message.
  final handle = ResourceHandle.fromFile(raf);
  final again = handle.toFile();
  print('read through the handle: ${String.fromCharCodes(again.readSync(11))}');
  again.closeSync();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
read through the handle: shared file
external factory ResourceHandle.fromSocket(Socket socket)

Creates wrapper around opened socket.

external factory ResourceHandle.fromRawSocket(RawSocket socket)

Creates wrapper around opened raw socket.

external factory ResourceHandle.fromRawDatagramSocket(RawDatagramSocket socket)

Creates wrapper around opened raw datagram socket.

external factory ResourceHandle.fromStdin(Stdin stdin)

Creates wrapper around current stdin.

Example
import 'raya:io';

void main() {
  // Wraps file descriptor 0 so it could be passed to another process over a Unix socket.
  final h = ResourceHandle.fromStdin(stdin);
  print('stdin handle created: ${h is ResourceHandle}');
}
Output from the Raya VM
stdin handle created: true
external factory ResourceHandle.fromStdout(Stdout stdout)

Creates wrapper around current stdout.

Example
import 'raya:io';

void main() {
  final h = ResourceHandle.fromStdout(stdout);
  final out = h.toFile();
  out.writeStringSync('written to stdout through a handle\n');
}
Output from the Raya VM
written to stdout through a handle
external factory ResourceHandle.fromReadPipe(ReadPipe pipe)
Example
import 'raya:io';

Future<void> main() async {
  final pipe = await Pipe.create();
  final handle = ResourceHandle.fromReadPipe(pipe.read);
  final reader = handle.toReadPipe();
  pipe.write.add([1, 2, 3]);
  await pipe.write.close();
  print('read through the handle: ${await reader.expand((c) => c).toList()}');
}
Output from the Raya VM
read through the handle: [1, 2, 3]
external factory ResourceHandle.fromWritePipe(WritePipe pipe)
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final pipe = await Pipe.create();
  final writer = ResourceHandle.fromWritePipe(pipe.write).toWritePipe();
  writer.write('via a write-pipe handle');
  await writer.close();
  print(await utf8.decoder.bind(pipe.read).join());
}
Output from the Raya VM
via a write-pipe handle

Methods

toFilemethod
RandomAccessFile toFile()

Extracts opened file from resource handle.

This can also be used when receiving stdin and stdout handles and read and write pipes.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method.

If this resource handle is not a file or stdio handle, the behavior of the returned RandomAccessFile is completely unspecified. Be very careful to avoid using a handle incorrectly.

Example
import 'raya:io';

void main() {
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final raf = File('${tmp.path}/b.txt').openSync(mode: FileMode.write);
  final f2 = ResourceHandle.fromFile(raf).toFile();
  f2.writeStringSync('written via toFile');
  f2.closeSync();
  print(File('${tmp.path}/b.txt').readAsStringSync());
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
written via toFile
toSocketmethod
Socket toSocket()

Extracts opened socket from resource handle.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method. If this resource handle is not a socket handle, the behavior of the returned Socket is completely unspecified. Be very careful to avoid using a handle incorrectly.

RawSocket toRawSocket()

Extracts opened raw socket from resource handle.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method.

If this resource handle is not a socket handle, the behavior of the returned RawSocket is completely unspecified. Be very careful to avoid using a handle incorrectly.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final got = server.first.then((c) => c.expand((d) => d).toList().whenComplete(c.destroy));
  final raw = await RawSocket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  final again = ResourceHandle.fromRawSocket(raw).toRawSocket();
  again.write([4, 2]);
  await again.close();
  await raw.close();
  print('server got: ${await got.timeout(t)}');
  await server.close();
}
Output from the Raya VM
server got: []
RawDatagramSocket toRawDatagramSocket()

Extracts opened raw datagram socket from resource handle.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method.

If this resource handle is not a datagram socket handle, the behavior of the returned RawDatagramSocket is completely unspecified. Be very careful to avoid using a handle incorrectly.

ReadPipe toReadPipe()

Extracts a read pipe from resource handle.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method.

If this resource handle is not a readable pipe, the behavior of the returned ReadPipe is completely unspecified. Be very careful to avoid using a handle incorrectly.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final pipe = await Pipe.create();
  final reader = ResourceHandle.fromReadPipe(pipe.read).toReadPipe();
  pipe.write.write('pipe text');
  await pipe.write.close();
  print(await utf8.decoder.bind(reader).join());
}
Output from the Raya VM
pipe text
WritePipe toWritePipe()

Extracts a write pipe from resource handle.

Since the ResourceHandle represents a single OS resource, none of toFile, toSocket, toRawSocket, or toRawDatagramSocket, toReadPipe, toWritePipe, can be called after a call to this method.

If this resource handle is not a writeable pipe, the behavior of the returned ReadPipe is completely unspecified. Be very careful to avoid using a handle incorrectly.

Example
import 'raya:io';

Future<void> main() async {
  final pipe = await Pipe.create();
  final w = ResourceHandle.fromWritePipe(pipe.write).toWritePipe();
  w.add([7, 8, 9]);
  await w.close();
  print('bytes: ${await pipe.read.expand((c) => c).toList()}');
}
Output from the Raya VM
bytes: [7, 8, 9]
abstract interface class SocketControlMessage

Control message part of the SocketMessage received by a call to RawSocket.readMessage.

Control messages could carry different information including ResourceHandle. If ResourceHandles are available as part of this message, they can be extracted via extractHandles.

Constructors

external factory SocketControlMessage.fromHandles(List<ResourceHandle> handles)

Creates a control message containing the provided handles.

This is used by the sender when it sends handles across the socket. Receiver can extract the handles from the message using extractHandles.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final file = File('${tmp.path}/secret.txt')..writeAsStringSync('passed by descriptor');
  final addr = InternetAddress('${tmp.path}/sock', type: InternetAddressType.unix);
  final server = await RawServerSocket.bind(addr, 0);
  final client = await RawSocket.connect(addr, 0).timeout(t);
  final peer = await server.first.timeout(t);
  client.sendMessage([SocketControlMessage.fromHandles([ResourceHandle.fromFile(file.openSync())])], [1]);
  await for (final e in peer.timeout(t)) {
    final m = e == RawSocketEvent.read ? peer.readMessage() : null;
    if (m == null) continue;
    final f = m.controlMessages.single.extractHandles().single.toFile();
    print('peer read: ${String.fromCharCodes(f.readSync(100))}');
    f.closeSync();
    break;
  }
  await client.close();
  await peer.close();
  await server.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
peer read: passed by descriptor

Properties

levelgetter
int get level

A platform specific value used to determine the kind of control message.

Together with type, these two integers identify the kind of control message in a platform specific way. For example, on Linux certain combinations of these values indicate that this is a control message that carries ResourceHandles.

typegetter
int get type

A platform specific value used to determine the kind of control message.

Together with level, these two integers identify the kind of control message in a platform specific way. For example, on Linux certain combinations of these values indicate that this is a control message that carries ResourceHandles.

datagetter
Uint8List get data

Actual bytes that were passed as part of the control message by the underlying platform.

The bytes are interpreted differently depending on the level and type. These actual bytes can be used to inspect and interpret non-handle-carrying messages.

Methods

List<ResourceHandle> extractHandles()

Extracts the list of handles embedded in this message.

This method must only be used to extract handles from messages received on a socket. It must not be used on a socket control message that is created locally, and has not been sent using RawSocket.sendMessage.

This method must only be called once. Calling it multiple times may cause duplicated handles with unspecified behavior.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final tmp = Directory.systemTemp.createTempSync('raya_ex_');
  final addr = InternetAddress('${tmp.path}/s', type: InternetAddressType.unix);
  final server = await RawServerSocket.bind(addr, 0);
  final client = await RawSocket.connect(addr, 0).timeout(t);
  final peer = await server.first.timeout(t);
  final files = [for (final n in ['a', 'b']) (File('${tmp.path}/$n')..writeAsStringSync(n)).openSync()];
  client.sendMessage([SocketControlMessage.fromHandles([for (final f in files) ResourceHandle.fromFile(f)])], [0]);
  await for (final e in peer.timeout(t)) {
    final m = e == RawSocketEvent.read ? peer.readMessage() : null;
    if (m == null) continue;
    final got = m.controlMessages.single.extractHandles().map((h) => h.toFile()).toList();
    print('handles: ${got.length}, contents: ${got.map((f) => String.fromCharCodes(f.readSync(1))).toList()}');
    got.forEach((f) => f.closeSync());
    break;
  }
  files.forEach((f) => f.closeSync());
  await client.close();
  await peer.close();
  await server.close();
  tmp.deleteSync(recursive: true);
}
Output from the Raya VM
handles: 2, contents: [a, b]
final class SocketMessage

A socket message received by a RawDatagramSocket.

A socket message consists of data bytes and controlMessages.

Constructors

SocketMessageconstructor
SocketMessage(this.data, this.controlMessages)
Example
import 'raya:io';
import 'raya:typed_data';

void main() {
  final m = SocketMessage(Uint8List.fromList([1, 2, 3]), []);
  print('data: ${m.data}, control messages: ${m.controlMessages.length}');
}
Output
data: [1, 2, 3], control messages: 0

Properties

datafield
final Uint8List data

The actual bytes of the message.

final List<SocketControlMessage> controlMessages

The control messages sent as part of this socket message.

This list can be empty.

abstract interface class RawDatagramSocket extends Stream<RawSocketEvent>

An unbuffered interface to a UDP socket.

The raw datagram socket delivers a Stream of RawSocketEvents in the same chunks as the underlying operating system receives them.

Note that the event RawSocketEvent.readClosed will never be received as an UDP socket cannot be closed by a remote peer.

It is not the same as a POSIX raw socket.

import 'raya:io';
import 'raya:typed_data';

void main() async {
  // Read the current time from an NTP server.
  final serverAddress = (await InternetAddress.lookup('pool.ntp.org')).first;
  final clientSocket = await RawDatagramSocket.bind(
      serverAddress.type == InternetAddressType.IPv6
          ? InternetAddress.anyIPv6
          : InternetAddress.anyIPv4,
      0);
  final ntpQuery = Uint8List(48);
  ntpQuery[0] = 0x23; // See RFC 5905 7.3

  clientSocket.listen((event) {
    switch (event) {
      case RawSocketEvent.read:
        final datagram = clientSocket.receive();
        // Parse `datagram.data`
        clientSocket.close();
        break;
      case RawSocketEvent.write:
        if (clientSocket.send(ntpQuery, serverAddress, 123) > 0) {
          clientSocket.writeEventsEnabled = false;
        }
        break;
      case RawSocketEvent.closed:
        break;
      default:
        throw "Unexpected event $event";
    }
  });
}

Static

bindstaticmethod
external static Future<RawDatagramSocket> bind(host, int port, {bool reuseAddress = true, bool reusePort = false, int ttl = 1})

Binds a socket to the given host and port.

When the socket is bound and has started listening on port, the returned future completes with the RawDatagramSocket of the bound socket.

The host can either be a String or an InternetAddress. If host is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback interface, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from any network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces, or use the IP address of a specific interface.

The reuseAddress should be set for all listeners that bind to the same address. Otherwise, it will fail with a SocketException.

The reusePort specifies whether the port can be reused.

The ttl sets time to live of a datagram sent on the socket.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final a = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  final b = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  a.send(utf8.encode('udp hello'), InternetAddress.loopbackIPv4, b.port);
  await for (final e in b) {
    if (e != RawSocketEvent.read) continue;
    final d = b.receive()!;
    print('got "${utf8.decode(d.data)}" from port ${d.port == a.port ? 'a' : d.port}');
    break;
  }
  a.close();
  b.close();
}
Output from the Raya VM
got "udp hello" from port a

Properties

abstract bool readEventsEnabled

Whether the RawDatagramSocket should listen for RawSocketEvent.read events.

Default is true.

abstract bool writeEventsEnabled

Whether the RawDatagramSocket should listen for RawSocketEvent.write events.

Default is true. This is a one-shot listener, and writeEventsEnabled must be set to true again to receive another write event.

abstract bool multicastLoopback

Whether multicast traffic is looped back to the host.

By default multicast loopback is enabled.

abstract int multicastHops

The maximum network hops for multicast packages originating from this socket.

For IPv4 this is referred to as TTL (time to live).

By default this value is 1 causing multicast traffic to stay on the local network.

multicastInterfacefielddeprecated
NetworkInterface? multicastInterface

The network interface used for outgoing multicast packages.

A value of null indicate that the system chooses the network interface to use.

By default this value is null

abstract bool broadcastEnabled

Whether IPv4 broadcast is enabled.

IPv4 broadcast needs to be enabled by the sender for sending IPv4 broadcast packages. By default IPv4 broadcast is disabled.

For IPv6 there is no general broadcast mechanism. Use multicast instead.

portgetter
int get port

The port used by this socket.

addressgetter
InternetAddress get address

The address used by this socket.

Methods

closemethod
void close()

Closes the datagram socket.

Example
import 'raya:io';

Future<void> main() async {
  final s = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  final events = <RawSocketEvent>[];
  final done = s.listen(events.add).asFuture<void>();
  s.close();
  await done;
  print('events after close: $events');
}
Output from the Raya VM
events after close: [RawSocketEvent.closed]
sendmethod
int send(List<int> buffer, InternetAddress address, int port)

Asynchronously sends a datagram.

Returns the number of bytes written. This will always be either the size of buffer or 0.

A return value of 0 indicates that sending the datagram would block and that the send call can be tried again.

A return value of the size of buffer indicates that a request to transmit the datagram was made to the operating system. It does not indicate that the operating system successfully sent the datagram. If a local failure to send the datagram occurs then an error event will be added to the Stream. If a networking or remote failure occurs then it will not be reported.

The maximum size of a IPv4 UDP datagram is 65535 bytes (including both data and headers) but the practical maximum size is likely to be much lower due to operating system limits and the network's maximum transmission unit (MTU).

Some IPv6 implementations may support payloads up to 4GB (see RFC-2675) but that support is limited (see RFC-6434) and has been removed in later standards (see RFC-8504).

Emperical testing by the Chromium team suggests that payloads later than 1350 cannot be reliably received.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final rx = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  final tx = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  print('bytes sent: ${tx.send([1, 2, 3, 4], InternetAddress.loopbackIPv4, rx.port)}');
  await for (final e in rx.timeout(t)) {
    final d = e == RawSocketEvent.read ? rx.receive() : null;
    if (d != null) {
      print('received: ${d.data}');
      break;
    }
  }
  rx.close();
  tx.close();
}
Output from the Raya VM
bytes sent: 4
received: [1, 2, 3, 4]
receivemethod
Datagram? receive()

Receives a datagram.

Returns null if there are no datagrams available.

Example
import 'raya:io';

Future<void> main() async {
  final rx = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  final tx = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  print('nothing queued yet: ${rx.receive()}');
  for (final n in [1, 2, 3]) {
    tx.send([n], InternetAddress.loopbackIPv4, rx.port);
  }
  final got = <int>[];
  await for (final e in rx) {
    if (e == RawSocketEvent.read) got.addAll(rx.receive()!.data);
    if (got.length == 3) break;
  }
  print('datagrams in order: $got');
  rx.close();
  tx.close();
}
Output from the Raya VM
nothing queued yet: null
datagrams in order: [1, 2, 3]
void joinMulticast(InternetAddress group, [NetworkInterface? interface])

Joins a multicast group.

If an error occur when trying to join the multicast group, an exception is thrown.

Example
import 'raya:io';

Future<void> main() async {
  final group = InternetAddress('239.10.20.30');
  final s = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
  try {
    s.joinMulticast(group);
    print('joined ${group.address}; multicast: ${group.isMulticast}');
    s.leaveMulticast(group);
  } on OSError {
    print('no multicast-capable interface here');
  }
  s.close();
}
Output from the Raya VM
joined 239.10.20.30; multicast: true
void leaveMulticast(InternetAddress group, [NetworkInterface? interface])

Leaves a multicast group.

If an error occur when trying to join the multicast group, an exception is thrown.

Example
import 'raya:io';

Future<void> main() async {
  final group = InternetAddress('239.1.1.1');
  final s = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
  try {
    s.joinMulticast(group);
    s.leaveMulticast(group);
    print('joined and left ${group.address}');
  } on OSError {
    print('no multicast-capable interface here');
  }
  s.close();
}
Output from the Raya VM
joined and left 239.1.1.1
Uint8List getRawOption(RawSocketOption option)

Reads low level information about the RawSocket.

See RawSocketOption for available options.

Returns RawSocketOption.value on success.

Throws an OSError on failure.

Example
import 'raya:io';

Future<void> main() async {
  final s = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  s.broadcastEnabled = true;
  final soBroadcast = Platform.isLinux ? 6 : 0x20;
  final v = s.getRawOption(RawSocketOption.fromInt(RawSocketOption.levelSocket, soBroadcast, 0));
  print('SO_BROADCAST is on: ${v.any((b) => b != 0)}');
  s.close();
}
Output from the Raya VM
SO_BROADCAST is on: true
void setRawOption(RawSocketOption option)

Customizes the RawSocket.

See RawSocketOption for available options.

Throws an OSError on failure.

Example
import 'raya:io';

Future<void> main() async {
  final s = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
  final soBroadcast = Platform.isLinux ? 6 : 0x20;
  s.setRawOption(RawSocketOption.fromBool(RawSocketOption.levelSocket, soBroadcast, true));
  print('broadcastEnabled now: ${s.broadcastEnabled}');
  s.close();
}
Output from the Raya VM
broadcastEnabled now: true
class SocketException implements IOException

Exception thrown when a socket operation fails.

Constructors

SocketExceptionconstructor
const SocketException(this.message, {this.osError, this.address, this.port})

Creates a SocketException with the provided values.

Example
import 'raya:io';

void main() {
  final e = SocketException('Connection refused', osError: const OSError('Connection refused', 61), address: InternetAddress.loopbackIPv4, port: 9);
  print('message: ${e.message}, port: ${e.port}, address: ${e.address?.address}');
}
Output from the Raya VM
message: Connection refused, port: 9, address: 127.0.0.1
const SocketException.closed()

Creates an exception reporting that a socket was used after it was closed.

Example
import 'raya:io';

void main() {
  const e = SocketException.closed();
  print('message: ${e.message}');
}
Output
message: Socket has been closed

Properties

messagefield
final String message

Description of the error.

osErrorfield
final OSError? osError

The underlying OS error.

If this exception is not thrown due to an OS error, the value is null.

addressfield
final InternetAddress? address

The address of the socket giving rise to the exception.

This is either the source or destination address of a socket, or it can be null if no socket end-point was involved in the cause of the exception.

portfield
final int? port

The port of the socket giving rise to the exception.

This is either the source or destination address of a socket, or it can be null if no socket end-point was involved in the cause of the exception.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

Future<void> main() async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final port = s.port;
  await s.close();
  try {
    await Socket.connect(InternetAddress.loopbackIPv4, port).timeout(const Duration(seconds: 2));
  } on SocketException catch (e) {
    print(e.toString().startsWith('SocketException: Connection refused'));
  }
}
Output from the Raya VM
true
class

Stdin

class Stdin extends _StdStream implements Stream<List<int>>

The standard input stream of the process.

Allows both synchronous and asynchronous reads from the standard input stream.

Mixing synchronous and asynchronous reads is undefined.

Properties

echoModegetter
external bool get echoMode

Whether echo mode is enabled on stdin.

If disabled, input from the console will not be echoed.

Default depends on the parent process, but is usually enabled.

On POSIX systems this mode is the echo local terminal mode. Before Raya, it also controlled the echonl mode, which is now controlled by echoNewlineMode.

On Windows this mode can only be enabled if lineMode is enabled as well.

echoModesetter
external set echoMode(bool echoMode)
external bool get echoNewlineMode

Whether echo newline mode is enabled on stdin.

If enabled, newlines from the terminal will be echoed even if the regular echoMode is disabled. This mode may require lineMode to be turned on to have an effect.

Default depends on the parent process, but is usually disabled.

On POSIX systems this mode is the echonl local terminal mode.

On Windows this mode cannot be set.

external set echoNewlineMode(bool echoNewlineMode)
lineModegetter
external bool get lineMode

Whether line mode is enabled on stdin.

If enabled, characters are delayed until a newline character is entered. If disabled, characters will be available as typed.

Default depends on the parent process, but is usually enabled.

On POSIX systems this mode is the icanon local terminal mode.

On Windows this mode can only be disabled if echoMode is disabled as well.

lineModesetter
external set lineMode(bool lineMode)
external bool get supportsAnsiEscapes

Whether connected to a terminal that supports ANSI escape sequences.

Not all terminals are recognized, and not all recognized terminals can report whether they support ANSI escape sequences, so this value is a best-effort attempt at detecting the support.

The actual escape sequence support may differ between terminals, with some terminals supporting more escape sequences than others, and some terminals even differing in behavior for the same escape sequence.

The ANSI color selection is generally supported.

Currently, a TERM environment variable containing the string xterm, screen, rxvt, or tmux will be taken as evidence that ANSI escape sequences are supported. On Windows, only versions of Windows 10 after v.1511 ("TH2", OS build 10586) will be detected as supporting the output of ANSI escape sequences, and only versions after v.1607 ("Anniversary Update", OS build 14393) will be detected as supporting the input of ANSI escape sequences.

bool get hasTerminal

Whether there is a terminal attached to stdin.

Methods

String? readLineSync({Encoding encoding = systemEncoding, bool retainNewlines = false})

Reads a line from stdin.

Blocks until a full line is available.

Lines may be terminated by either <CR><LF> or <LF>. On Windows, in cases where the stdioType of stdin is StdioType.terminal, the terminator may also be a single <CR>.

Input bytes are converted to a string by encoding. If encoding is omitted, it defaults to systemEncoding.

If retainNewlines is false, the returned string will not include the final line terminator. If true, the returned string will include the line terminator. Default is false.

If end-of-file is reached after any bytes have been read from stdin, that data is returned without a line terminator. Returns null if no bytes preceded the end of input.

external int readByteSync()

Synchronously reads a byte from stdin.

This call will block until a byte is available.

If at end of file, -1 is returned.

class

Stdout

class Stdout extends _StdSink implements IOSink

An IOSink connected to either the standard out or error of the process.

Provides a blocking IOSink, so using it to write will block until the output is written.

In some situations this blocking behavior is undesirable as it does not provide the same non-blocking behavior that raya:io in general exposes. Use the property nonBlocking to get an IOSink which has the non-blocking behavior.

This class can also be used to check whether stdout or stderr is connected to a terminal and query some terminal properties.

The addError API is inherited from StreamSink and calling it will result in an unhandled asynchronous error unless there is an error handler on done.

The lineTerminator field is used by the write, writeln, writeAll and writeCharCode methods to translate "\n". By default, "\n" is output literally.

Properties

bool get hasTerminal

Whether there is a terminal attached to stdout.

int get terminalColumns

The number of columns of the terminal.

If no terminal is attached to stdout, a StdoutException is thrown. See hasTerminal for more info.

int get terminalLines

The number of lines of the terminal.

If no terminal is attached to stdout, a StdoutException is thrown. See hasTerminal for more info.

bool get supportsAnsiEscapes

Whether connected to a terminal that supports ANSI escape sequences.

Not all terminals are recognized, and not all recognized terminals can report whether they support ANSI escape sequences, so this value is a best-effort attempt at detecting the support.

The actual escape sequence support may differ between terminals, with some terminals supporting more escape sequences than others, and some terminals even differing in behavior for the same escape sequence.

The ANSI color selection is generally supported.

Currently, a TERM environment variable containing the string xterm will be taken as evidence that ANSI escape sequences are supported. On Windows, only versions of Windows 10 after v.1511 ("TH2", OS build 10586) will be detected as supporting the output of ANSI escape sequences, and only versions after v.1607 ("Anniversary Update", OS build 14393) will be detected as supporting the input of ANSI escape sequences.

IOSink get nonBlocking

A non-blocking IOSink for the same output.

The returned IOSink will be initialized with an encoding of UTF-8 and will not do line ending conversion.

class StdoutException implements IOException

Exception thrown by some operations of Stdout

Constructors

StdoutExceptionconstructor
const StdoutException(this.message, [this.osError])
Example
import 'raya:io';

void main() {
  const e = StdoutException('Broken pipe', OSError('Broken pipe', 32));
  print('message: ${e.message}, errno: ${e.osError?.errorCode}');
}
Output
message: Broken pipe, errno: 32

Properties

messagefield
final String message

Message describing cause of the exception.

osErrorfield
final OSError? osError

The underlying OS error, if available.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const StdoutException('Error setting terminal mode'));
}
Output
StdoutException: Error setting terminal mode
class StdinException implements IOException

Exception thrown by some operations of Stdin

Constructors

StdinExceptionconstructor
const StdinException(this.message, [this.osError])
Example
import 'raya:io';

void main() {
  const e = StdinException('Error setting terminal echo mode', OSError('Not a tty', 25));
  print('message: ${e.message}, errno: ${e.osError?.errorCode}');
}
Output
message: Error setting terminal echo mode, errno: 25

Properties

messagefield
final String message

Message describing cause of the exception.

osErrorfield
final OSError? osError

The underlying OS error, if available.

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const StdinException('Error reading from stdin'));
}
Output
StdinException: Error reading from stdin
final class StdioType

The type of object a standard IO stream can be attached to.

Static

terminalconstant
static const StdioType terminal = const StdioType._("terminal")
pipeconstant
static const StdioType pipe = const StdioType._("pipe")
fileconstant
static const StdioType file = const StdioType._("file")
otherconstant
static const StdioType other = const StdioType._("other")

Properties

namefield
final String name

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  for (final t in [StdioType.terminal, StdioType.pipe, StdioType.file, StdioType.other]) {
    print(t);
  }
}
Output
StdioType: terminal
StdioType: pipe
StdioType: file
StdioType: other
final class SystemEncoding extends Encoding

The system encoding is the current code page on Windows and UTF-8 on Linux and Mac.

Constructors

SystemEncodingconstructor
const SystemEncoding()

Creates a const SystemEncoding.

Users should use the top-level constant, systemEncoding.

Example
import 'raya:io';

void main() {
  const enc = SystemEncoding();
  print('name: ${enc.name}');
  print('same as systemEncoding: ${enc.name == systemEncoding.name}');
}
Output
name: system
same as systemEncoding: true

Properties

namegetter
String get name
encodergetter
Converter<String, List<int>> get encoder
decodergetter
Converter<List<int>, String> get decoder

Methods

encodemethod
List<int> encode(String input)
Example
import 'raya:io';

void main() {
  print('encode(ok): ${systemEncoding.encode('ok')}');
}
Output from the Raya VM
encode(ok): [111, 107]
decodemethod
String decode(List<int> encoded)
Example
import 'raya:io';

void main() {
  final r = Process.runSync('echo', ['hi'], stdoutEncoding: null);
  print('raw bytes: ${r.stdout}');
  print('decoded: ${systemEncoding.decode(r.stdout as List<int>).trim()}');
}
Output from the Raya VM
raw bytes: [104, 105, 10]
decoded: hi
abstract interface class RawSynchronousSocket

A low-level class for communicating synchronously over a TCP socket.

Warning: RawSynchronousSocket should probably only be used to connect to 'localhost'. The operations below will block the calling thread to wait for a response from the network. The thread can process no other events while waiting for these operations to complete. RawSynchronousSocket is not suitable for applications that require high performance or asynchronous I/O such as a server. Instead such applications should use the non-blocking sockets and asynchronous operations in the Socket or RawSocket classes.

Static

connectSyncstaticmethod
external static RawSynchronousSocket connectSync(host, int port)

Creates a new socket connection and returns a RawSynchronousSocket.

The host can either be a String or an InternetAddress. If host is a String, connectSync will perform a InternetAddress.lookup and try all returned InternetAddresses, until connected. Unless a connection was established, the error from the first failing connection is returned.

Example
import 'raya:io';
import 'raya:isolate';

// A tiny echo server on its own isolate, so the blocking client can't stall it.
void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  await for (final c in s) {
    c.listen((d) => c..add(d)..close());
    await s.close();
  }
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final p = await port.first as int;
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, p);
  sock.writeFromSync([1, 2, 3]);
  print('echoed: ${sock.readSync(3)}');
  sock.closeSync();
}
Output from the Raya VM
echoed: [1, 2, 3]

Properties

portgetter
int get port

The port used by this socket.

int get remotePort

The remote port connected to by this socket.

addressgetter
InternetAddress get address

The InternetAddress used to connect this socket.

InternetAddress get remoteAddress

The remote InternetAddress connected to by this socket.

Methods

availablemethod
int available()

The number of received and unread bytes in the socket that can be read.

Example
import 'raya:io';
import 'raya:isolate';

void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  final c = await s.first;
  c.add([9, 9, 9, 9]);
  await c.close();
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, await port.first as int);
  final first = sock.readSync(1);
  print('read 1 byte: $first, available now: ${sock.available() <= 3}');
  sock.closeSync();
}
Output from the Raya VM
read 1 byte: [9], available now: true
closeSyncmethod
void closeSync()

Closes the RawSynchronousSocket.

Once closeSync has been called, attempting to call readSync, readIntoSync, writeFromSync, remoteAddress, and remotePort will cause a SocketException to be thrown.

Example
import 'raya:io';

Future<void> main() async {
  final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, server.port);
  sock.writeFromSync([1]);
  sock.closeSync();
  try {
    sock.writeFromSync([2]);
  } on SocketException {
    print('write after closeSync: SocketException');
  }
  await server.close();
}
Output from the Raya VM
write after closeSync: SocketException
int readIntoSync(List<int> buffer, [int start = 0, int? end])

Reads bytes into an existing buffer.

Reads bytes and writes then into the range of buffer from start to end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Returns the number of bytes read. This maybe be less than end - start if the file doesn't have that many bytes to read.

Example
import 'raya:io';
import 'raya:isolate';

void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  final c = await s.first;
  c.add([10, 20, 30]);
  await c.close();
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, await port.first as int);
  final buf = List.filled(5, 0);
  final n = sock.readIntoSync(buf, 1, 4); // blocks until 3 bytes arrive
  print('read $n bytes: $buf');
  sock.closeSync();
}
Output from the Raya VM
read 3 bytes: [0, 10, 20, 30, 0]
readSyncmethod
List<int>? readSync(int bytes)

Reads up to bytes bytes from the socket.

Blocks and waits for a response of up to a specified number of bytes sent by the socket. bytes specifies the maximum number of bytes to be read. Returns the list of bytes read, which could be less than the value specified by bytes.

Example
import 'raya:io';
import 'raya:isolate';
import 'raya:convert';

void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  final c = await s.first;
  c.write('sync!');
  await c.close();
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, await port.first as int);
  print('readSync(5): ${utf8.decode(sock.readSync(5)!)}');
  sock.closeSync();
}
Output from the Raya VM
readSync(5): sync!
shutdownmethod
void shutdown(SocketDirection direction)

Shuts down a socket in the provided direction.

Calling shutdown will never throw an exception and calling it several times is supported. If both SocketDirection.receive and SocketDirection.send directions are closed, the socket is closed completely, the same as if closeSync has been called.

Example
import 'raya:io';
import 'raya:isolate';

void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  final c = await s.first;
  final got = await c.expand((d) => d).toList(); // ends when the client shuts down sending
  c.add([got.length]);
  await c.close();
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, await port.first as int);
  sock.writeFromSync([1, 2, 3, 4]);
  sock.shutdown(SocketDirection.send);
  print('server counted ${sock.readSync(1)} bytes');
  sock.closeSync();
}
Output from the Raya VM
server counted [4] bytes
void writeFromSync(List<int> buffer, [int start = 0, int? end])

Writes from a buffer to the socket.

Will read the buffer from index start to index end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.

Example
import 'raya:io';
import 'raya:isolate';
import 'raya:convert';

void server(SendPort ready) async {
  final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  ready.send(s.port);
  final c = await s.first;
  final text = await utf8.decoder.bind(c).join();
  c.write(text.toUpperCase());
  await c.close();
}

Future<void> main() async {
  final port = ReceivePort();
  await Isolate.spawn(server, port.sendPort);
  final sock = RawSynchronousSocket.connectSync(InternetAddress.loopbackIPv4, await port.first as int);
  final bytes = utf8.encode('--shout--');
  sock.writeFromSync(bytes, 2, 7);
  sock.shutdown(SocketDirection.send);
  print(utf8.decode(sock.readSync(5)!));
  sock.closeSync();
}
Output from the Raya VM
SHOUT
abstract class HttpServer implements Stream<HttpRequest>

A server that delivers content, such as web pages, using the HTTP protocol.

Note: HttpServer provides low-level HTTP functionality.

HttpServer is a Stream that provides HttpRequest objects. Each HttpRequest has an associated HttpResponse object. The server responds to a request by writing to that HttpResponse object. The following example shows how to bind an HttpServer to an IPv6 InternetAddress on port 80 (the standard port for HTTP servers) and how to listen for requests. Port 80 is the default HTTP port. However, on most systems accessing this requires super-user privileges. For local testing consider using a non-reserved port (1024 and above).

import 'raya:io';

void main() async {
  var server = await HttpServer.bind(InternetAddress.anyIPv6, 80);
  await server.forEach((HttpRequest request) {
    request.response.write('Hello, world!');
    request.response.close();
  });
}

Incomplete requests, in which all or part of the header is missing, are ignored, and no exceptions or HttpRequest objects are generated for them. Likewise, when writing to an HttpResponse, any Socket exceptions are ignored and any future writes are ignored.

The HttpRequest exposes the request headers and provides the request body, if it exists, as a Stream of data. If the body is unread, it is drained when the server writes to the HttpResponse or closes it.

Bind with a secure HTTPS connection

Use bindSecure to create an HTTPS server.

The server presents a certificate to the client. The certificate chain and the private key are set in the SecurityContext object that is passed to bindSecure.

import 'raya:io';

void main() async {
  var chain =
      Platform.script.resolve('certificates/server_chain.pem').toFilePath();
  var key = Platform.script.resolve('certificates/server_key.pem').toFilePath();
  var context = SecurityContext()
    ..useCertificateChain(chain)
    ..usePrivateKey(key, password: 'rayaraya');
  var server =
      await HttpServer.bindSecure(InternetAddress.anyIPv6, 443, context);
  await server.forEach((HttpRequest request) {
    request.response.write('Hello, world!');
    request.response.close();
  });
}

The certificates and keys are PEM files, which can be created and managed with the tools in OpenSSL.

Constructors

factory HttpServer.listenOn(ServerSocket serverSocket)

Attaches the HTTP server to an existing ServerSocket. When the HttpServer is closed, the HttpServer will just detach itself, closing current connections but not closing serverSocket.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  final server = HttpServer.listenOn(socket); // serve HTTP on an existing socket
  server.listen((req) => req.response..write('served on a ServerSocket')..close());
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', socket.port, '/')).close().timeout(t);
  print(await utf8.decoder.bind(res).join().timeout(t));
  client.close(force: true);
  await server.close(force: true);
  await socket.close();
}
Output from the Raya VM
served on a ServerSocket

Static

bindstaticmethod
static Future<HttpServer> bind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false})

Starts listening for HTTP requests on the specified address and port.

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only. However, if the address is InternetAddress.loopbackIPv6, only IP version 6 (IPv6) connections will be accepted.

If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

The optional argument shared specifies whether additional HttpServer objects can bind to the same combination of address, port and v6Only. If shared is true and more HttpServers from this isolate or other isolates are bound to the port, then the incoming connections will be distributed among all the bound HttpServers. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response
    ..headers.contentType = ContentType.text
    ..write('you asked for ${req.uri.path}')
    ..close());
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/hello')).close().timeout(const Duration(seconds: 2));
  print('${res.statusCode}: ${await utf8.decoder.bind(res).join()}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
200: you asked for /hello
bindSecurestaticmethod
static Future<HttpServer> bindSecure(address, int port, SecurityContext context, {int backlog = 0, bool v6Only = false, bool requestClientCertificate = false, bool shared = false})

The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.loopbackIPv4 or InternetAddress.loopbackIPv6. To allow for incoming connection from the network use either one of the values InternetAddress.anyIPv4 or InternetAddress.anyIPv6 to bind to all interfaces or the IP address of a specific interface.

If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only.

If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.

The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0 (the default) a reasonable value will be chosen by the system.

If requestClientCertificate is true, the server will request clients to authenticate with a client certificate. The server will advertise the names of trusted issuers of client certificates, getting them from a SecurityContext, where they have been set using SecurityContext.setClientAuthorities.

The optional argument shared specifies whether additional HttpServer objects can bind to the same combination of address, port and v6Only. If shared is true and more HttpServers from this isolate or other isolates are bound to the port, then the incoming connections will be distributed among all the bound HttpServers. Connections can be distributed over multiple isolates this way.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final d = Directory.systemTemp.createTempSync('raya_ex_');
  // A throwaway self-signed certificate for localhost (needs openssl on PATH).
  Process.runSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
    '-keyout', '${d.path}/k.pem', '-out', '${d.path}/c.pem', '-days', '1', '-subj', '/CN=localhost',
    '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-addext', 'basicConstraints=critical,CA:TRUE',
    '-addext', 'keyUsage=critical,digitalSignature,keyCertSign', '-addext', 'extendedKeyUsage=serverAuth']);
  final server = await HttpServer.bindSecure(InternetAddress.loopbackIPv4, 0, (SecurityContext()..useCertificateChain('${d.path}/c.pem')..usePrivateKey('${d.path}/k.pem')));
  server.listen((req) => req.response..write('https ok, ${req.uri.scheme}')..close());
  final client = HttpClient(context: SecurityContext()..setTrustedCertificates('${d.path}/c.pem'));
  final res = await (await client.getUrl(Uri.parse('https://localhost:${server.port}/'))).close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
  d.deleteSync(recursive: true);
}
Output from the Raya VM
https ok,

Properties

String? serverHeader

Gets and sets the default value of the Server header for all responses generated by this HttpServer.

If serverHeader is null, no Server header will be added to each response.

The default value is null.

HttpHeaders get defaultResponseHeaders

Default set of headers added to all response objects.

By default the following headers are in this set:

Content-Type: text/plain; charset=utf-8 X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block

If the Server header is added here and the serverHeader is set as well then the value of serverHeader takes precedence.

bool autoCompress

Whether the HttpServer should compress the content, if possible.

The content can only be compressed when the response is using chunked Transfer-Encoding and the incoming request has gzip as an accepted encoding in the Accept-Encoding header.

The default value is false (compression disabled). To enable, set autoCompress to true.

Duration? idleTimeout

Gets or sets the timeout used for idle keep-alive connections. If no further request is seen within idleTimeout after the previous request was completed, the connection is dropped.

Default is 120 seconds.

Note that it may take up to 2 * idleTimeout before a idle connection is aborted.

To disable, set idleTimeout to null.

portgetter
int get port

The port that the server is listening on.

This is the actual port used when a port of zero is specified in the bind or bindSecure call.

addressgetter
InternetAddress get address

The address that the server is listening on.

This is the actual address used when the original address was specified as a hostname.

set sessionTimeout(int timeout)

Sets the timeout, in seconds, for sessions of this HttpServer.

The default timeout is 20 minutes.

Example
import 'raya:io';
import 'raya:async';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0)..sessionTimeout = 1; // seconds
  final expired = Completer<void>();
  server.listen((req) {
    req.session.onTimeout = expired.complete;
    req.response.close();
  });
  final client = HttpClient();
  await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2)).then((r) => r.drain<void>());
  await expired.future;
  print('session expired after 1 s without requests');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
session expired after 1 s without requests

Methods

closemethod
Future close({bool force = false})

Permanently stops this HttpServer from listening for new connections. This closes the Stream of HttpRequests with a done event. The returned future completes when the server is stopped. For a server started using bind or bindSecure this means that the port listened on no longer in use.

If force is true, active connections will be closed immediately.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  final finished = server.drain<void>();
  await server.close(force: true);
  await finished;
  print('server closed; its request stream is done');
}
Output from the Raya VM
server closed; its request stream is done
HttpConnectionsInfo connectionsInfo()

An HttpConnectionsInfo object summarizing the number of current connections handled by the server.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  print('before any request: total ${server.connectionsInfo().total}');
  server.listen((req) {
    final info = server.connectionsInfo();
    req.response
      ..write('active while handling: ${info.active}')
      ..close();
  });
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
before any request: total 0
active while handling: 1
class HttpConnectionsInfo

Summary statistics about an HttpServers current socket connections.

Properties

totalfield
int total

Total number of socket connections.

activefield
int active

Number of active connections where actual request/response processing is active.

idlefield
int idle

Number of idle connections held by clients as persistent connections.

closingfield
int closing

Number of connections which are preparing to close.

Note: These connections are also part of the active count as they might still be sending data to the client before finally closing.

abstract interface class HttpHeaders

Headers for HTTP requests and responses.

In some situations, headers are immutable:

In these situations, the mutating methods throw exceptions.

For all operations on HTTP headers the header name is case-insensitive.

To set the value of a header use the set method:

Request.headers.set(HttpHeaders.cacheControlHeader, 'max-age=3600, must-revalidate');

To retrieve the value of a header use the value method:

print(request.headers.value(HttpHeaders.userAgentHeader));

An HttpHeaders object holds a list of values for each name as the standard allows. In most cases a name holds only a single value, The most common mode of operation is to use set for setting a value, and value for retrieving a value.

Static

acceptHeaderconstant
static const acceptHeader = "accept"
static const acceptCharsetHeader = "accept-charset"
static const acceptEncodingHeader = "accept-encoding"
static const acceptLanguageHeader = "accept-language"
static const acceptRangesHeader = "accept-ranges"
static const accessControlAllowCredentialsHeader = 'access-control-allow-credentials'
static const accessControlAllowHeadersHeader = 'access-control-allow-headers'
static const accessControlAllowMethodsHeader = 'access-control-allow-methods'
static const accessControlAllowOriginHeader = 'access-control-allow-origin'
static const accessControlExposeHeadersHeader = 'access-control-expose-headers'
static const accessControlMaxAgeHeader = 'access-control-max-age'
static const accessControlRequestHeadersHeader = 'access-control-request-headers'
static const accessControlRequestMethodHeader = 'access-control-request-method'
ageHeaderconstant
static const ageHeader = "age"
allowHeaderconstant
static const allowHeader = "allow"
static const authorizationHeader = "authorization"
static const cacheControlHeader = "cache-control"
static const connectionHeader = "connection"
static const contentEncodingHeader = "content-encoding"
static const contentLanguageHeader = "content-language"
static const contentLengthHeader = "content-length"
static const contentLocationHeader = "content-location"
static const contentMD5Header = "content-md5"
static const contentRangeHeader = "content-range"
static const contentTypeHeader = "content-type"
dateHeaderconstant
static const dateHeader = "date"
etagHeaderconstant
static const etagHeader = "etag"
expectHeaderconstant
static const expectHeader = "expect"
static const expiresHeader = "expires"
fromHeaderconstant
static const fromHeader = "from"
hostHeaderconstant
static const hostHeader = "host"
static const ifMatchHeader = "if-match"
static const ifModifiedSinceHeader = "if-modified-since"
static const ifNoneMatchHeader = "if-none-match"
static const ifRangeHeader = "if-range"
static const ifUnmodifiedSinceHeader = "if-unmodified-since"
static const lastModifiedHeader = "last-modified"
static const locationHeader = "location"
static const maxForwardsHeader = "max-forwards"
pragmaHeaderconstant
static const pragmaHeader = "pragma"
static const proxyAuthenticateHeader = "proxy-authenticate"
static const proxyAuthorizationHeader = "proxy-authorization"
rangeHeaderconstant
static const rangeHeader = "range"
static const refererHeader = "referer"
static const retryAfterHeader = "retry-after"
serverHeaderconstant
static const serverHeader = "server"
teHeaderconstant
static const teHeader = "te"
static const trailerHeader = "trailer"
static const transferEncodingHeader = "transfer-encoding"
static const upgradeHeader = "upgrade"
static const userAgentHeader = "user-agent"
varyHeaderconstant
static const varyHeader = "vary"
viaHeaderconstant
static const viaHeader = "via"
static const warningHeader = "warning"
static const wwwAuthenticateHeader = "www-authenticate"
static const contentDisposition = "content-disposition"
cookieHeaderconstant
static const cookieHeader = "cookie"
static const setCookieHeader = "set-cookie"
static const generalHeaders
static const entityHeaders
static const responseHeaders
static const requestHeaders

Properties

datefield
DateTime? date

The date specified by the dateHeader header, if any.

expiresfield
DateTime? expires

The date and time specified by the expiresHeader header, if any.

DateTime? ifModifiedSince

The date and time specified by the ifModifiedSinceHeader header, if any.

hostfield
String? host

The value of the hostHeader header, if any.

portfield
int? port

The value of the port part of the hostHeader header, if any.

ContentType? contentType

The ContentType of the contentTypeHeader header, if any.

int contentLength

The value of the contentLengthHeader header, if any.

The value is negative if there is no content length set.

late bool persistentConnection

Whether the connection is persistent (keep-alive).

late bool chunkedTransferEncoding

Whether the connection uses chunked transfer encoding.

Reflects and modifies the value of the transferEncodingHeader header.

Methods

valuemethod
String? value(String name)

Convenience method for the value for a single valued header.

The value must not have more than one value.

Returns null if there is no header with the provided name.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    print('user-agent: ${req.headers.value('user-agent')}');
    print('x-missing: ${req.headers.value('x-missing')}');
    req.response.close();
  });
  final client = HttpClient()..userAgent = 'raya-example';
  await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2)).then((r) => r.drain<void>());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
user-agent: raya-example
x-missing: null
addmethod
void add(String name, Object value, {bool preserveHeaderCase = false})

Adds a header value.

The header named name will have a string value derived from value added to its list of values.

Some headers are single valued, and for these, adding a value will replace a previous value. If the value is a DateTime, an HTTP date format will be applied. If the value is an Iterable, each element will be added separately. For all other types the default Object.toString method will be used.

Header names are converted to lower-case unless preserveHeaderCase is set to true. If two header names are the same when converted to lower-case, they are considered to be the same header, with one set of values.

The current case of the a header name is that of the name used by the last set or add call for that header.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    print('x-tag values: ${req.headers['x-tag']}');
    req.response.close();
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/');
  req.headers.add('X-Tag', 'red');
  req.headers.add('X-Tag', 'blue'); // add keeps earlier values
  await (await req.close()).drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
x-tag values: [red, blue]
setmethod
void set(String name, Object value, {bool preserveHeaderCase = false})

Sets the header name to value.

Removes all existing values for the header named name and then adds value to it.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    print('accept: ${req.headers['accept']}');
    req.response.close();
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/');
  req.headers.add('Accept', 'text/html');
  req.headers.set('Accept', 'application/json'); // replaces every earlier value
  await (await req.close()).drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
accept: [application/json]
removemethod
void remove(String name, Object value)

Removes a specific value for a header name.

Some headers have system supplied values which cannot be removed. For all other headers and values, the value is converted to a string in the same way as for add, then that string value is removed from the current values of name. If there are no remaining values for name, the header is no longer considered present.

Example
import 'raya:io';

Future<void> main() async {
  final client = HttpClient();
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    print('x-flag on the server: ${req.headers['x-flag']}');
    req.response.close();
  });
  final req = await client.get('127.0.0.1', server.port, '/');
  req.headers
    ..add('X-Flag', 'a')
    ..add('X-Flag', 'b')
    ..remove('X-Flag', 'a');
  await (await req.close()).drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
x-flag on the server: [b]
removeAllmethod
void removeAll(String name)

Removes all values for the specified header name.

Some headers have system supplied values which cannot be removed. All other values for name are removed. If there are no remaining values for name, the header is no longer considered present.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    print('user-agent after removeAll: ${req.headers.value('user-agent')}');
    req.response.close();
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/');
  req.headers.removeAll(HttpHeaders.userAgentHeader);
  await (await req.close()).drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
user-agent after removeAll: null
forEachmethod
void forEach(void Function(String name, List<String> values) action)

Performs the action on each header.

The action function is called with each header's name and a list of the header's values. The casing of the name string is determined by the last add or set operation for that particular header, which defaults to lower-casing the header name unless explicitly set to preserve the case.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    final names = <String>[];
    req.headers.forEach((name, values) => names.add(name));
    print('request header names: ${names..sort()}');
    req.response.close();
  });
  final client = HttpClient()..userAgent = 'x';
  final req = await client.get('127.0.0.1', server.port, '/');
  req.headers.set('X-Request-Id', '7');
  await (await req.close()).drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
request header names: [accept-encoding, host, user-agent, x-request-id]
noFoldingmethod
void noFolding(String name)

Disables folding for the header named name when sending the HTTP header.

By default, multiple header values are folded into a single header line by separating the values with commas.

The 'set-cookie' header has folding disabled by default.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    req.response.headers
      ..add('X-Item', 'a')
      ..add('X-Item', 'b')
      ..noFolding('X-Item'); // send two header lines, not "a, b"
    req.response.close();
  });
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  s.write('GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
  final text = String.fromCharCodes(await s.expand((c) => c).toList().timeout(t));
  print(text.split('\r\n').where((l) => l.startsWith('x-item')).toList());
  s.destroy();
  await server.close(force: true);
}
Output from the Raya VM
[x-item: a, x-item: b]
clearmethod
void clear()

Removes all headers.

Some headers have system supplied values which cannot be removed. All other header values are removed, and header names with not remaining values are no longer considered present.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    req.response.headers
      ..set('X-A', '1')
      ..clear()
      ..set('X-B', '2');
    req.response.close();
  });
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2));
  print('x-a: ${res.headers.value('x-a')}, x-b: ${res.headers.value('x-b')}');
  await res.drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
x-a: null, x-b: 2

Operators

operator []operator
List<String>? operator [](String name)

The values for the header named name.

Returns null if there is no header with the provided name, otherwise returns a new list containing the current values. Not that modifying the list does not change the header.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    req.response.headers.add('Set-Cookie', 'a=1');
    req.response.headers.add('Set-Cookie', 'b=2');
    req.response.close();
  });
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2));
  print("headers['set-cookie']: ${res.headers['set-cookie']}");
  print("headers['x-none']: ${res.headers['x-none']}");
  await res.drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
headers['set-cookie']: [a=1, b=2]
headers['x-none']: null
abstract interface class HeaderValue

Representation of a header value in the form:

value; parameter1=value1; parameter2=value2

HeaderValue can be used to conveniently build and parse header values on this form.

Parameter values can be omitted, in which case the value is parsed as null. Values can be doubled quoted to allow characters outside of the RFC 7230 token characters and backslash sequences can be used to represent the double quote and backslash characters themselves.

To build an "accepts" header with the value

Text/plain; q=0.3, text/html

Use code like this:

HttpClientRequest request =... Var v = HeaderValue("text/plain", {"q": "0.3"}); request.headers.add(HttpHeaders.acceptHeader, v); request.headers.add(HttpHeaders.acceptHeader, "text/html");

To parse the header values use the parse static method.

HttpRequest request =... List<String> values = request.headersHttpHeaders.acceptHeader; values.forEach((value) { HeaderValue v = HeaderValue.parse(value); // Use v.value and v.parameters });

An instance of HeaderValue is immutable.

Constructors

factory HeaderValue([String value = "", Map<String, String?> parameters = const {}])

Creates a new header value object setting the value and parameters.

Example
import 'raya:io';

void main() {
  final v = HeaderValue('form-data', {'name': 'file', 'filename': 'a b.txt'});
  print(v);
  print('value: ${v.value}, filename: ${v.parameters['filename']}');
}
Output
form-data; name=file; filename="a b.txt"
value: form-data, filename: a b.txt

Static

parsestaticmethod
static HeaderValue parse(String value, {String parameterSeparator = ";", String? valueSeparator, bool preserveBackslash = false})

Creates a new header value object from parsing a header value string with both value and optional parameters.

Example
import 'raya:io';

void main() {
  final v = HeaderValue.parse('text/html; charset=utf-8; q=0.9');
  print('value: ${v.value}');
  print('parameters: ${v.parameters}');
  final cache = HeaderValue.parse('no-cache, max-age=0', parameterSeparator: ',');
  print('cache: ${cache.value}, ${cache.parameters}');
}
Output
value: text/html
parameters: {charset: utf-8, q: 0.9}
cache: no-cache, {max-age: 0}

Properties

valuegetter
String get value

The value of the header.

Map<String, String?> get parameters

A map of parameters.

This map cannot be modified.

Methods

toStringmethod
String toString()

Returns the formatted string representation in the form:

value; parameter1=value1; parameter2=value2
Example
import 'raya:io';

void main() {
  print(HeaderValue('attachment', {'filename': 'report.pdf'}));
  print(HeaderValue('no-store'));
}
Output
attachment; filename=report.pdf
no-store
abstract interface class HttpSession implements Map

The HttpRequest.session of an HttpRequest.

Stores arbitrary information about a browser session on the server. This information is stored in memory so it will be lost when the server exits.

A cookie named "RAYASESSID" is stored on the browser to associate the HttpSession with a particular client.

import 'raya:io';

void main() async {
  HttpServer.bind("localhost", 8080).then((server) {
    server.listen((request) {
      final session = request.session;
      if (session.isNew) {
        session["cart"] = [];
      }
      if (request.uri.queryParameters['buy'] != null) {
        final item = request.uri.queryParameters['buy'];
        session["cart"].add(item);
      }
      session["cart"].cast<String>().forEach(request.response.writeln);
      request.response.close();
    });
  });
}

Properties

idgetter
String get id

The id of the current session.

onTimeoutsetter
void set onTimeout(void Function() callback)

Sets a callback that will be called when the session is timed out.

Calling this again will overwrite the previous value.

Example
import 'raya:io';
import 'raya:async';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0)..sessionTimeout = 1;
  final timedOut = Completer<String>();
  server.listen((req) {
    final s = req.session..['user'] = 'ada';
    s.onTimeout = () => timedOut.complete('session for ${s['user']} timed out');
    req.response.close();
  });
  final client = HttpClient();
  await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2)).then((r) => r.drain<void>());
  print(await timedOut.future);
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
session for ada timed out
isNewgetter
bool get isNew

Whether the session has not yet been sent to the client.

Methods

destroymethod
void destroy()

Destroys the session.

This terminates the session and any further connections with this id will be given a new id and session.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    final s = req.session;
    print('new session: ${s.isNew}');
    s.destroy(); // like logging out
    req.response.close();
  });
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2));
  print('cookie set for the session: ${res.cookies.any((c) => c.name == 'RAYASESSID' || c.name.contains('SESS'))}');
  await res.drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
new session: true
cookie set for the session: false
abstract interface class ContentType implements HeaderValue

A MIME/IANA media type used as the value of the HttpHeaders.contentTypeHeader header.

A ContentType is immutable.

Constructors

factory ContentType(String primaryType, String subType, {String? charset, Map<String, String?> parameters = const {}})

Creates a new content type object setting the primary type and sub type. The charset and additional parameters can also be set using charset and parameters. If charset is passed and parameters contains charset as well the passed charset will override the value in parameters. Keys passed in parameters will be converted to lower case. The charset entry, whether passed as charset or in parameters, will have its value converted to lower-case.

Example
import 'raya:io';

void main() {
  final ct = ContentType('application', 'json', charset: 'utf-8');
  print(ct);
  print('mimeType: ${ct.mimeType}, charset: ${ct.charset}');
  print('same as ContentType.json: ${ct.toString() == ContentType.json.toString()}');
}
Output
application/json; charset=utf-8
mimeType: application/json, charset: utf-8
same as ContentType.json: true

Static

textstaticfield
static final text

Content type for plain text using UTF-8 encoding.

Text/plain; charset=utf-8

htmlstaticfield
static final html

Content type for HTML using UTF-8 encoding.

Text/html; charset=utf-8

jsonstaticfield
static final json

Content type for JSON using UTF-8 encoding.

Application/json; charset=utf-8

binarystaticfield
static final binary

Content type for binary data.

Application/octet-stream

parsestaticmethod
static ContentType parse(String value)

Creates a new content type object from parsing a Content-Type header value. As primary type, sub type and parameter names and values are not case sensitive all these values will be converted to lower case. Parsing this string

Text/html; charset=utf-8

Will create a content type object with primary type "text", subtype "html" and parameter "charset" with value "utf-8". There may be more parameters supplied, but they are not recognized by this class.

Example
import 'raya:io';

void main() {
  final ct = ContentType.parse('Text/HTML; charset=ISO-8859-1');
  print('primary ${ct.primaryType}, sub ${ct.subType}, charset ${ct.charset}');
  print('mimeType: ${ct.mimeType}');
}
Output
primary text, sub html, charset iso-8859-1
mimeType: text/html

Properties

mimeTypegetter
String get mimeType

Gets the MIME type and subtype, without any parameters.

For the full content type text/html;charset=utf-8, the mimeType value is the string text/html.

String get primaryType

Gets the primary type.

For the full content type text/html;charset=utf-8, the primaryType value is the string text.

subTypegetter
String get subType

Gets the subtype.

For the full content type text/html;charset=utf-8, the subType value is the string html. May be the empty string.

charsetgetter
String? get charset

Gets the character set, if any.

For the full content type text/html;charset=utf-8, the charset value is the string utf-8.

final class SameSite

Cookie cross-site availability configuration.

The value of Cookie.sameSite, which defines whether an HTTP cookie is available from other sites or not.

Has three possible values: lax, strict and none.

Static

laxconstant
static const lax = SameSite._("Lax")

Default value, cookie with this value will generally not be sent on cross-site requests, unless the user is navigated to the original site.

strictconstant
static const strict = SameSite._("Strict")

Cookie with this value will never be sent on cross-site requests.

noneconstant
static const none = SameSite._("None")

Cookie with this value will be sent in all requests.

Cookie.secure must also be set to true, otherwise the none value will have no effect.

valuesconstant
static const List<SameSite> values = [lax, strict, none]

Properties

namefield
final String name

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(SameSite.lax);
  print(SameSite.strict);
  print(SameSite.none);
}
Output
SameSite=Lax
SameSite=Strict
SameSite=None
abstract interface class HttpRequest implements Stream<Uint8List>

A server-side object that contains the content of and information about an HTTP request.

HttpRequest objects are generated by an HttpServer, which listens for HTTP requests on a specific host and port. For each request received, the HttpServer, which is a Stream, generates an HttpRequest object and adds it to the stream.

An HttpRequest object delivers the body content of the request as a stream of byte lists. The object also contains information about the request, such as the method, URI, and headers.

In the following code, an HttpServer listens for HTTP requests. When the server receives a request, it uses the HttpRequest object's method property to dispatch requests.

Final HOST = InternetAddress.loopbackIPv4; final PORT = 80;

HttpServer.bind(HOST, PORT).then((_server) { _server.listen((HttpRequest request) { switch (request.method) { case 'GET': handleGetRequest(request); break; case 'POST'... } }, onError: handleError); // listen failed. }).catchError(handleError);

An HttpRequest object provides access to the associated HttpResponse object through the response property. The server writes its response to the body of the HttpResponse object. For example, here's a function that responds to a request:

Void handleGetRequest(HttpRequest req) { HttpResponse res = req.response; res.write('Received request ${req.method}: ${req.uri.path}'); res.close; }

Properties

int get contentLength

The content length of the request body.

If the size of the request body is not known in advance, this value is -1.

methodgetter
String get method

The method, such as 'GET' or 'POST', for the request.

urigetter
Uri get uri

The URI for the request.

This provides access to the path and query string for the request.

Uri get requestedUri

The requested URI for the request.

If the request URI is absolute (e.g. 'https://www.example.com/foo') then it is returned as-is. Otherwise, the returned URI is reconstructed by using the request URI path (e.g. '/foo') and HTTP header fields.

To reconstruct the scheme, the 'X-Forwarded-Proto' header is used. If it is not present then the socket type of the connection is used i.e. if the connection is made through a SecureSocket then the scheme is 'https', otherwise it is 'http'.

To reconstruct the host, the 'X-Forwarded-Host' header is used. If it is not present then the 'Host' header is used. If neither is present then the host name of the server is used.

headersgetter
HttpHeaders get headers

The request headers.

The returned HttpHeaders are immutable.

cookiesgetter
List<Cookie> get cookies

The cookies in the request, from the "Cookie" headers.

bool get persistentConnection

The persistent connection state signaled by the client.

X509Certificate? get certificate

The client certificate of the client making the request.

This value is null if the connection is not a secure TLS or SSL connection, or if the server does not request a client certificate, or if the client does not provide one.

sessiongetter
HttpSession get session

The session for the given request.

If the session is being initialized by this call, HttpSession.isNew is true for the returned session. See HttpServer.sessionTimeout on how to change default timeout.

String get protocolVersion

The HTTP protocol version used in the request, either "1.0" or "1.1".

HttpConnectionInfo? get connectionInfo

Information about the client connection.

Returns null if the socket is not available.

responsegetter
HttpResponse get response

The HttpResponse object, used for sending back the response to the client.

If the contentLength of the body isn't 0, and the body isn't being read, any write calls on the HttpResponse automatically drain the request body.

abstract interface class HttpResponse implements IOSink

An HTTP response, which returns the headers and data from the server to the client in response to an HTTP request.

Every HttpRequest object provides access to the associated HttpResponse object through the response property. The server sends its response to the client by writing to the HttpResponse object.

Writing the response

This class implements IOSink. After the header has been set up, the methods from IOSink, such as writeln, can be used to write the body of the HTTP response. Use the close method to close the response and send it to the client.

Server.listen((HttpRequest request) { request.response.write('Hello, world!'); request.response.close; });

When one of the IOSink methods is used for the first time, the request header is sent. Calling any methods that change the header after it is sent throws an exception.

If no "Content-Type" header is set then a default of "text/plain; charset=utf-8" is used and string data written to the IOSink will be encoded using UTF-8.

Setting the headers

The HttpResponse object has a number of properties for setting up the HTTP headers of the response. When writing string data through the IOSink, the encoding used is determined from the "charset" parameter of the "Content-Type" header.

HttpResponse response =... response.headers.contentType = ContentType("application", "json", charset: "utf-8"); response.write(...); // Strings written will be UTF-8 encoded.

If no charset is provided the default of ISO-8859-1 (Latin 1) will be used.

HttpResponse response =... response.headers.add(HttpHeaders.contentTypeHeader, "text/plain"); response.write(...); // Strings written will be ISO-8859-1 encoded.

If a charset is provided but it is not recognized, then the "Content-Type" header will include that charset but string data will be encoded using ISO-8859-1 (Latin 1).

Properties

int contentLength

Gets and sets the content length of the response. If the size of the response is not known in advance set the content length to -1, which is also the default if not set.

int statusCode

The status code of the response.

Any integer value is accepted. For the official HTTP status codes use the fields from HttpStatus. If no status code is explicitly set the default value HttpStatus.ok is used.

The status code must be set before the body is written to. Setting the status code after writing to the response body or closing the response will throw a StateError.

late String reasonPhrase

The reason phrase for the response.

If no reason phrase is explicitly set, a default reason phrase is provided.

The reason phrase must be set before the body is written to. Setting the reason phrase after writing to the response body or closing the response will throw a StateError.

late bool persistentConnection

Gets and sets the persistent connection state. The initial value of this property is the persistent connection state from the request.

Duration? deadline

Set and get the deadline for the response. The deadline is timed from the time it's set. Setting a new deadline will override any previous deadline. When a deadline is exceeded, the response will be closed and any further data ignored.

To disable a deadline, set the deadline to null.

The deadline is null by default.

bool bufferOutput

Gets or sets if the HttpResponse should buffer output.

Default value is true.

__Note__: Disabling buffering of the output can result in very poor performance, when writing many small chunks.

headersgetter
HttpHeaders get headers

Returns the response headers.

The response headers can be modified until the response body is written to or closed. After that they become immutable.

cookiesgetter
List<Cookie> get cookies

Cookies to set in the client (in the 'set-cookie' header).

HttpConnectionInfo? get connectionInfo

Gets information about the client connection. Returns null if the socket is not available.

Methods

redirectmethod
Future redirect(Uri location, {int status = HttpStatus.movedTemporarily})

Respond with a redirect to location.

The URI in location should be absolute, but there are no checks to enforce that.

By default the HTTP status code HttpStatus.movedTemporarily (302) is used for the redirect, but an alternative one can be specified using the status argument.

This method will also call close, and the returned future is the future returned by close.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    if (req.uri.path == '/old') {
      req.response.redirect(Uri.parse('/new'));
    } else {
      req.response..write('landed on ${req.uri.path}')..close();
    }
  });
  final client = HttpClient();
  final res = await (await client.get('127.0.0.1', server.port, '/old')).close().timeout(const Duration(seconds: 2));
  print('${await utf8.decoder.bind(res).join()}, redirects followed: ${res.redirects.length}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
landed on /new, redirects followed: 1
Future<Socket> detachSocket({bool writeHeaders = true})

Detaches the underlying socket from the HTTP server. When the socket is detached the HTTP server will no longer perform any operations on it.

This is normally used when an HTTP upgrade request is received and the communication should continue with a different protocol.

If writeHeaders is true, the status line and headers will be written to the socket before it's detached. If false, the socket is detached immediately, without any data written to the socket. Default is true.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    req.response.statusCode = HttpStatus.switchingProtocols;
    req.response.headers.set('Upgrade', 'raw');
    final socket = await req.response.detachSocket(); // headers sent, now plain TCP
    socket.write('raw bytes after the upgrade');
    await socket.close();
    socket.destroy();
  });
  final s = await Socket.connect(InternetAddress.loopbackIPv4, server.port).timeout(t);
  s.write('GET / HTTP/1.1\r\nHost: x\r\n\r\n');
  final text = String.fromCharCodes(await s.expand((c) => c).toList().timeout(t));
  print('status line: ${text.split('\r\n').first}');
  print('after headers: ${text.split('\r\n\r\n').last}');
  s.destroy();
  await server.close(force: true);
}
Output from the Raya VM
status line: HTTP/1.1 101 Switching Protocols
after headers: raw bytes after the upgrade
abstract interface class HttpClient

An HTTP client for communicating with an HTTP server.

Note: You should avoid directly using HttpClient to make HTTP requests. You can use HttpClient indirectly through the [IOClient] adapter in [package:http]. Using a higher-level library, like [package:http], allows you to switch implementations with minimal changes to your code. For example, package:http [Client] has implementations for the browser and implementations that use platform native HTTP clients on Android and iOS. Unlike HttpClient, these native implementations work with the proxies, VPNs, etc.

Sends HTTP requests to an HTTP server and receives responses. Maintains state, including session cookies and other cookies, between multiple requests to the same server.

HttpClient contains a number of methods to send an HttpClientRequest to an Http server and receive an HttpClientResponse back. For example, you can use the get, getUrl, post, and postUrl methods for GET and POST requests, respectively.

Making a simple GET request: an example

A getUrl request is a two-step process, triggered by two Futures. When the first future completes with an HttpClientRequest, the underlying network connection has been established, but no data has been sent. In the callback function for the first future, the HTTP headers and body can be set on the request. Either the first write to the request object or a call to close sends the request to the server.

When the HTTP response is received from the server, the second future, which is returned by close, completes with an HttpClientResponse object. This object provides access to the headers and body of the response. The body is available as a stream implemented by HttpClientResponse. If a body is present, it must be read. Otherwise, it leads to resource leaks. Consider using HttpClientResponse.drain if the body is unused.

var client = HttpClient();
try {
  HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
  // Optionally set up headers...
  // Optionally write to the request object...
  HttpClientResponse response = await request.close();
  // Process the response
  final stringData = await response.transform(utf8.decoder).join();
  print(stringData);
} finally {
  client.close();
}

The future for HttpClientRequest is created by methods such as getUrl and open.

HTTPS connections

An HttpClient can make HTTPS requests, connecting to a server using the TLS (SSL) secure networking protocol. Calling getUrl with an https: scheme will work automatically, if the server's certificate is signed by a root CA (certificate authority) on the default list of well-known trusted CAs, compiled by Mozilla.

To add a custom trusted certificate authority, or to send a client certificate to servers that request one, pass a SecurityContext object as the optional context argument to the HttpClient constructor. The desired security options can be set on the SecurityContext object.

Headers

All HttpClient requests set the following header by default:

Accept-Encoding: gzip

This allows the HTTP server to use gzip compression for the body if possible. If this behavior is not desired set the Accept-Encoding header to something else. To turn off gzip compression of the response, clear this header:

Request.headers.removeAll(HttpHeaders.acceptEncodingHeader)

Closing the HttpClient

HttpClient supports persistent connections and caches network connections to reuse them for multiple requests whenever possible. This means that network connections can be kept open for some time after a request has completed. Use HttpClient.close to force the HttpClient object to shut down and to close the idle network connections.

Turning proxies on and off

By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment. To turn off the use of proxies set the findProxy property to null.

HttpClient client = HttpClient; client.findProxy = null;

Constructors

HttpClientfactory
factory HttpClient({SecurityContext? context})
Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response..write('ok')..close());
  final client = HttpClient()
    ..userAgent = 'raya-docs'
    ..connectionTimeout = const Duration(seconds: 5)
    ..idleTimeout = const Duration(seconds: 2);
  final res = await (await client.getUrl(Uri.parse('http://127.0.0.1:${server.port}/'))).close().timeout(const Duration(seconds: 2));
  print('${res.statusCode} ${await utf8.decoder.bind(res).join()}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
200 ok

Static

static const int defaultHttpPort = 80
static const int defaultHttpsPort = 443
static set enableTimelineLogging(bool value)

Enable logging of HTTP requests from all HttpClients to the developer timeline.

Default is false.

Example
import 'raya:io';

void main() {
  HttpClient.enableTimelineLogging = true; // shows requests in the timeline tools
  print('timeline logging: ${HttpClient.enableTimelineLogging}');
  HttpClient.enableTimelineLogging = false;
  print('timeline logging: ${HttpClient.enableTimelineLogging}');
}
Output from the Raya VM
timeline logging: true
timeline logging: false
static bool get enableTimelineLogging

Current state of HTTP request logging from all HttpClients to the developer timeline.

Default is false.

static String findProxyFromEnvironment(Uri url, {Map<String, String>? environment})

Function for resolving the proxy server to be used for an HTTP connection from the proxy configuration specified through environment variables.

The following environment variables are taken into account:

http_proxy https_proxy no_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY

[:http_proxy:] and [:HTTP_PROXY:] specify the proxy server to use for http:// urls. Use the format [:hostname:port:]. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.

[:https_proxy:] and [:HTTPS_PROXY:] specify the proxy server to use for https:// urls. Use the format [:hostname:port:]. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.

[:no_proxy:] and [:NO_PROXY:] specify a comma separated list of postfixes of hostnames for which not to use the proxy server. E.g. The value "localhost,127.0.0.1" will make requests to both "localhost" and "127.0.0.1" not use a proxy. If both are set the lower case one takes precedence.

To activate this way of resolving proxies assign this function to the findProxy property on the HttpClient.

HttpClient client = HttpClient; client.findProxy = HttpClient.findProxyFromEnvironment;

If you don't want to use the system environment you can use a different one by wrapping the function.

HttpClient client = HttpClient; client.findProxy = (url) { return HttpClient.findProxyFromEnvironment( url, environment: {"http_proxy"... "no_proxy"...}); }

If a proxy requires authentication it is possible to configure the username and password as well. Use the format [:username:password@hostname:port:] to include the username and password. Alternatively the API addProxyCredentials can be used to set credentials for proxies which require authentication.

Example
import 'raya:io';

void main() {
  final env = {'http_proxy': 'proxy.local:3128', 'no_proxy': 'localhost,.internal'};
  for (final url in ['http://example.com/', 'http://wiki.internal/', 'http://localhost:8080/']) {
    print('$url -> ${HttpClient.findProxyFromEnvironment(Uri.parse(url), environment: env)}');
  }
}
Output
http://example.com/ -> PROXY proxy.local:3128
http://wiki.internal/ -> DIRECT
http://localhost:8080/ -> DIRECT

Properties

Duration idleTimeout

Gets and sets the idle timeout of non-active persistent (keep-alive) connections.

The default value is 15 seconds.

Duration? connectionTimeout

Gets and sets the connection timeout.

When connecting to a new host exceeds this timeout, a SocketException is thrown. The timeout applies only to connections initiated after the timeout is set.

When this is null, the OS default timeout is used. The default is null.

int? maxConnectionsPerHost

Gets and sets the maximum number of live connections, to a single host.

Increasing this number may lower performance and take up unwanted system resources.

To disable, set to null.

Default is null.

bool autoUncompress

Gets and sets whether the body of a response will be automatically uncompressed.

The body of an HTTP response can be compressed. In most situations providing the un-compressed body is most convenient. Therefore the default behavior is to un-compress the body. However in some situations (e.g. implementing a transparent proxy) keeping the uncompressed stream is required.

NOTE: Headers in the response are never modified. This means that when automatic un-compression is turned on the value of the header Content-Length will reflect the length of the original compressed body. Likewise the header Content-Encoding will also have the original value indicating compression.

NOTE: Automatic un-compression is only performed if the Content-Encoding header value is gzip.

This value affects all responses produced by this client after the value is changed.

To disable, set to false.

Default is true.

String? userAgent

Gets and sets the default value of the User-Agent header for all requests generated by this HttpClient.

The default value is Raya/<version> (raya:io).

If the userAgent is set to null, no default User-Agent header will be added to each request.

void set authenticate(Future<bool> Function(Uri url, String scheme, String? realm)? f)

Sets the function to be called when a site is requesting authentication.

The URL requested, the authentication scheme and the security realm from the server are passed in the arguments f.url, f.scheme and f.realm.

The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addCredentials before completing the Future with the value true.

If the Future completes with true the request will be retried using the updated credentials, however, the retried request will not carry the original request payload. Otherwise response processing will continue normally.

If it is known that the remote server requires authentication for all requests, it is advisable to use addCredentials directly, or manually set the 'authorization' header on the request to avoid the overhead of a failed request, or issues due to missing request payload on retried request.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    final auth = req.headers.value('authorization');
    if (auth == null) {
      req.response
        ..statusCode = 401
        ..headers.set('WWW-Authenticate', 'Basic realm="docs"');
    } else {
      req.response.write('welcome');
    }
    req.response.close();
  });
  final client = HttpClient();
  client.authenticate = (url, scheme, realm) async {
    print('asked for $scheme credentials, realm "$realm"');
    client.addCredentials(url, realm!, HttpClientBasicCredentials('ada', 'pw'));
    return true;
  };
  final res = await (await client.get('127.0.0.1', server.port, '/')).close().timeout(const Duration(seconds: 2));
  print('${res.statusCode}: ${String.fromCharCodes(await res.expand((c) => c).toList())}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
asked for Basic credentials, realm "docs"
200: welcome
void set connectionFactory(Future<ConnectionTask<Socket>> Function(Uri url, String? proxyHost, int? proxyPort)? f)

Sets the function used to create socket connections.

The URL requested (e.g. through getUrl) and proxy configuration (f.proxyHost and f.proxyPort) are passed as arguments. f.proxyHost and f.proxyPort will be null if the connection is not made through a proxy.

Since connections may be reused based on host and port, it is important that the function not ignore f.proxyHost and f.proxyPort if they are not null. If proxies are not meaningful for the returned Socket, you can set findProxy to use a direct connection.

For example:

import "raya:io";

void main() async {
  HttpClient client = HttpClient()
    ..connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) {
        assert(proxyHost == null);
        assert(proxyPort == null);
        var address = InternetAddress("/var/run/docker.sock",
            type: InternetAddressType.unix);
        return Socket.startConnect(address, 0);
    }
    ..findProxy = (Uri uri) => 'DIRECT';

  final request = await client.getUrl(Uri.parse("http://ignored/v1.41/info"));
  final response = await request.close();
  print(response.statusCode);
  await response.drain();
  client.close();
}
Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response..write('host header: ${req.headers.host}')..close());
  final client = HttpClient()
    // Every request goes to the local server, whatever the URL says.
    ..connectionFactory = (url, proxyHost, proxyPort) => Socket.startConnect(InternetAddress.loopbackIPv4, server.port);
  final res = await (await client.getUrl(Uri.parse('http://api.example.invalid/v1'))).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
host header: api.example.invalid
findProxysetter
void set findProxy(String Function(Uri url)? f)

Sets the function used to resolve the proxy server to be used for opening an HTTP connection to the specified url. If this function is not set, direct connections will always be used.

The string returned by f must be in the format used by browser PAC (proxy auto-config) scripts. That is either

"DIRECT"

For using a direct connection or

"PROXY host:port"

For using the proxy server host on port port.

A configuration can contain several configuration elements separated by semicolons, e.g.

"PROXY host:port; PROXY host2:port2; DIRECT"

The static function findProxyFromEnvironment on this class can be used to implement proxy server resolving based on environment variables.

Example
import 'raya:io';

Future<void> main() async {
  // The local server plays an HTTP proxy: it receives the absolute URL.
  final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  proxy.listen((req) => req.response..write('proxy saw ${req.uri}')..close());
  final client = HttpClient()..findProxy = (url) => 'PROXY 127.0.0.1:${proxy.port}';
  final res = await (await client.getUrl(Uri.parse('http://example.invalid/page'))).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await proxy.close(force: true);
}
Output from the Raya VM
proxy saw http://example.invalid/page
void set authenticateProxy(Future<bool> Function(String host, int port, String scheme, String? realm)? f)

Sets the function to be called when a proxy is requesting authentication.

Information on the proxy in use, the authentication scheme and the security realm for the authentication are passed in the arguments f.host, f.port, f.scheme and f.realm.

The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addProxyCredentials before completing the Future with the value true.

If the Future completes with true the request will be retried using the updated credentials. Otherwise response processing will continue normally.

Example
import 'raya:io';

Future<void> main() async {
  final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  proxy.listen((req) {
    if (req.headers.value('proxy-authorization') == null) {
      req.response
        ..statusCode = 407
        ..headers.set('Proxy-Authenticate', 'Basic realm="corp"');
    } else {
      req.response.write('through the proxy');
    }
    req.response.close();
  });
  final client = HttpClient()..findProxy = (url) => 'PROXY 127.0.0.1:${proxy.port}';
  client.authenticateProxy = (host, port, scheme, realm) async {
    client.addProxyCredentials(host, port, realm!, HttpClientBasicCredentials('me', 'pw'));
    return true;
  };
  final res = await (await client.getUrl(Uri.parse('http://example.invalid/'))).close().timeout(const Duration(seconds: 2));
  print('${res.statusCode}: ${String.fromCharCodes(await res.expand((c) => c).toList())}');
  client.close(force: true);
  await proxy.close(force: true);
}
Output from the Raya VM
200: through the proxy
void set badCertificateCallback(bool Function(X509Certificate cert, String host, int port)? callback)

Sets a callback that will decide whether to accept a secure connection with a server certificate that cannot be authenticated by any of our trusted root certificates.

When a secure HTTP request is made, using this HttpClient, and the server returns a server certificate that cannot be authenticated, the callback is called asynchronously with the X509Certificate object and the server's hostname and port. If the value of badCertificateCallback is null, the bad certificate is rejected, as if the callback returned false

If the callback returns true, the secure connection is accepted and the Future<HttpClientRequest> that was returned from the call making the request completes with a valid HttpRequest object. If the callback returns false, the Future<HttpClientRequest> completes with an exception.

If a bad certificate is received on a connection attempt, the library calls the function that was the value of badCertificateCallback at the time the request is made, even if the value of badCertificateCallback has changed since then.

Example
import 'raya:io';

void main() {
  final client = HttpClient();
  // Called for TLS certificates that fail verification; return true to accept anyway.
  client.badCertificateCallback = (cert, host, port) => host == 'localhost';
  print('callback installed: accepts self-signed certificates only for localhost');
  client.close();
}
Output from the Raya VM
callback installed: accepts self-signed certificates only for localhost
keyLogsetter
void set keyLog(Function(String line)? callback)

Sets a callback that will be called when new TLS keys are exchanged with the server. It will receive one line of text in [NSS Key Log Format] for each call. Writing these lines to a file will allow tools (such as Wireshark) to decrypt communication between the this client and the server. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:

Final log = File('keylog.txt'); final client = HttpClient; client.keyLog = (line) => log.writeAsStringSync(line, mode: FileMode.append);

Example
import 'raya:io';

void main() {
  final lines = <String>[];
  // Receives TLS session keys in NSS key log format, for tools like Wireshark.
  final client = HttpClient()..keyLog = lines.add;
  print('key log callback set; plain HTTP produces ${lines.length} lines');
  client.close();
}
Output from the Raya VM
key log callback set; plain HTTP produces 0 lines

Methods

openmethod
Future<HttpClientRequest> open(String method, String host, int port, String path)

Opens an HTTP connection.

The HTTP method to use is specified in method, the server is specified using host and port, and the path (including a possible query) is specified using path. The path may also contain a URI fragment, which will be ignored.

The Host header for the request will be set to the value host:port (if host is an IP address, it will still be used in the Host header). This can be overridden through the HttpClientRequest interface before the request is sent.

For additional information on the sequence of events during an HTTP transaction, and the objects returned by the futures, see the overall documentation for the class HttpClient.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response..write('${req.method} ${req.uri}')..close());
  final client = HttpClient();
  final res = await (await client.open('OPTIONS', '127.0.0.1', server.port, '/items?all=1')).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
OPTIONS /items?all=1
openUrlmethod
Future<HttpClientRequest> openUrl(String method, Uri url)

Opens an HTTP connection.

The HTTP method is specified in method and the URL to use in url.

The Host header for the request will be set to the value

Still be used in the Host header). This can be overridden through the HttpClientRequest interface before the request is sent.

For additional information on the sequence of events during an HTTP transaction, and the objects returned by the futures, see the overall documentation for the class HttpClient.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response..write('${req.method} ${req.uri.path}')..close());
  final client = HttpClient();
  final url = Uri.parse('http://127.0.0.1:${server.port}/reports/7');
  final res = await (await client.openUrl('PROPFIND', url)).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
PROPFIND /reports/7
getmethod
Future<HttpClientRequest> get(String host, int port, String path)

Opens an HTTP connection using the GET method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/items/1');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
GET /items/1, body:
getUrlmethod
Future<HttpClientRequest> getUrl(Uri url)

Opens an HTTP connection using the GET method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.getUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
GET /items/1, body:
postmethod
Future<HttpClientRequest> post(String host, int port, String path)

Opens an HTTP connection using the POST method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.post('127.0.0.1', server.port, '/items/1');
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
POST /items/1, body: {"n": 1}
postUrlmethod
Future<HttpClientRequest> postUrl(Uri url)

Opens an HTTP connection using the POST method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.postUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
POST /items/1, body: {"n": 1}
putmethod
Future<HttpClientRequest> put(String host, int port, String path)

Opens an HTTP connection using the PUT method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.put('127.0.0.1', server.port, '/items/1');
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
PUT /items/1, body: {"n": 1}
putUrlmethod
Future<HttpClientRequest> putUrl(Uri url)

Opens an HTTP connection using the PUT method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.putUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
PUT /items/1, body: {"n": 1}
deletemethod
Future<HttpClientRequest> delete(String host, int port, String path)

Opens an HTTP connection using the DELETE method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.delete('127.0.0.1', server.port, '/items/1');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
DELETE /items/1, body:
deleteUrlmethod
Future<HttpClientRequest> deleteUrl(Uri url)

Opens an HTTP connection using the DELETE method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.deleteUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
DELETE /items/1, body:
patchmethod
Future<HttpClientRequest> patch(String host, int port, String path)

Opens an HTTP connection using the PATCH method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.patch('127.0.0.1', server.port, '/items/1');
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
PATCH /items/1, body: {"n": 1}
patchUrlmethod
Future<HttpClientRequest> patchUrl(Uri url)

Opens an HTTP connection using the PATCH method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.patchUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  req.write('{"n": 1}');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print(await utf8.decoder.bind(res).join());
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
PATCH /items/1, body: {"n": 1}
headmethod
Future<HttpClientRequest> head(String host, int port, String path)

Opens an HTTP connection using the HEAD method.

The server is specified using host and port, and the path (including a possible query) is specified using path.

See open for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.head('127.0.0.1', server.port, '/items/1');
  final res = await req.close().timeout(const Duration(seconds: 2));
  print('status ${res.statusCode}, content-length ${res.headers.contentLength}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
status 200, content-length 21
headUrlmethod
Future<HttpClientRequest> headUrl(Uri url)

Opens an HTTP connection using the HEAD method.

The URL to use is specified in url.

See openUrl for details.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final reply = '${req.method} ${req.uri.path}, body: ${await utf8.decoder.bind(req).join()}';
    req.response
      ..headers.contentLength = reply.length
      ..write(reply);
    await req.response.close();
  });
  final client = HttpClient();
  final req = await client.headUrl(Uri.parse('http://127.0.0.1:${server.port}/items/1'));
  final res = await req.close().timeout(const Duration(seconds: 2));
  print('status ${res.statusCode}, content-length ${res.headers.contentLength}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
status 200, content-length 21
void addCredentials(Uri url, String realm, HttpClientCredentials credentials)

Add credentials to be used for authorizing HTTP requests.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    final auth = req.headers.value('authorization');
    if (auth == null) {
      req.response
        ..statusCode = 401
        ..headers.set('WWW-Authenticate', 'Basic realm="admin"');
    } else {
      req.response.write('authorized with $auth');
    }
    req.response.close();
  });
  final client = HttpClient();
  final base = Uri.parse('http://127.0.0.1:${server.port}/');
  client.addCredentials(base, 'admin', HttpClientBasicCredentials('ada', 'pw'));
  final res = await (await client.getUrl(base.resolve('admin'))).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
authorized with Basic YWRhOnB3
void addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials)

Add credentials to be used for authorizing HTTP proxies.

Example
import 'raya:io';

Future<void> main() async {
  final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  proxy.listen((req) {
    final auth = req.headers.value('proxy-authorization');
    if (auth == null) {
      req.response
        ..statusCode = 407
        ..headers.set('Proxy-Authenticate', 'Basic realm="corp"');
    } else {
      req.response.write('proxy accepted $auth');
    }
    req.response.close();
  });
  final client = HttpClient()..findProxy = (url) => 'PROXY 127.0.0.1:${proxy.port}';
  client.addProxyCredentials('127.0.0.1', proxy.port, 'corp', HttpClientBasicCredentials('me', 'pw'));
  final res = await (await client.getUrl(Uri.parse('http://example.invalid/'))).close().timeout(const Duration(seconds: 2));
  print(String.fromCharCodes(await res.expand((c) => c).toList()));
  client.close(force: true);
  await proxy.close(force: true);
}
Output from the Raya VM
proxy accepted Basic bWU6cHc=
closemethod
void close({bool force = false})

Shuts down the HTTP client.

If force is false (the default) the HttpClient will be kept alive until all active connections are done. If force is true any active connections will be closed to immediately release all resources. These closed connections will receive an error event to indicate that the client was shut down. In both cases trying to establish a new connection after calling close will throw an exception.

Example
import 'raya:io';

Future<void> main() async {
  final client = HttpClient();
  client.close(); // let open requests finish, then shut down
  try {
    await client.get('127.0.0.1', 1, '/');
  } on StateError catch (e) {
    print('request after close: ${e.message}');
  }
}
Output from the Raya VM
request after close: Client is closed
abstract interface class HttpClientRequest implements IOSink

HTTP request for a client connection.

To set up a request, set the headers using the headers property provided in this class and write the data to the body of the request. HttpClientRequest is an IOSink. Use the methods from IOSink, such as writeCharCode, to write the body of the HTTP request. When one of the IOSink methods is used for the first time, the request header is sent. Calling any methods that change the header after it is sent throws an exception.

When writing string data through the IOSink the encoding used is determined from the "charset" parameter of the "Content-Type" header.

var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.headers.contentType =
    ContentType('application', 'json', charset: 'utf-8');
request.write('text content👍🎯'); // Strings written will be UTF-8 encoded.

If no charset is provided the default of ISO-8859-1 (Latin 1) is used.

var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.headers.add(HttpHeaders.contentTypeHeader, "text/plain");
request.write('blåbærgrød'); // Strings written will be ISO-8859-1 encoded

An exception is thrown if you use an unsupported encoding and the write method being used takes a string parameter.

Properties

bool persistentConnection

The requested persistent connection state.

The default value is true.

bool followRedirects

Whether to follow redirects automatically.

Set this property to false if this request should not automatically follow redirects. The default is true.

Automatic redirect will only happen for "GET" and "HEAD" requests and only for the status codes HttpStatus.movedPermanently (301), HttpStatus.found (302), HttpStatus.movedTemporarily (302, alias for HttpStatus.found), HttpStatus.seeOther (303), HttpStatus.temporaryRedirect (307) and HttpStatus.permanentRedirect (308). For HttpStatus.seeOther (303) automatic redirect will also happen for "POST" requests with the method changed to "GET" when following the redirect.

All headers added to the request will be added to the redirection request(s) except when forwarding sensitive headers like "Authorization", "WWW-Authenticate", "Proxy-Authorization", "Proxy-Authenticate", and "Cookie". Those headers will be skipped if following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but a redirect to "bar.com" will not.

Any body send with the request will not be part of the redirection request(s).

For precise control of redirect handling, set this property to false and make a separate HTTP request to process the redirect. For example:

final client = HttpClient();
var uri = Uri.parse("http://localhost/");
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
while (response.isRedirect) {
  response.drain();
  final location = response.headers.value(HttpHeaders.locationHeader);
  if (location != null) {
    uri = uri.resolve(location);
    request = await client.getUrl(uri);
    // Set the body or headers as desired.
    request.followRedirects = false;
    response = await request.close();
  }
}
// Do something with the final response.
int maxRedirects

Set this property to the maximum number of redirects to follow when followRedirects is true. If this number is exceeded an error event will be added with a RedirectException.

The default value is 5.

methodgetter
String get method

The method of the request.

urigetter
Uri get uri

The uri of the request.

int contentLength

Gets and sets the content length of the request.

If the size of the request is not known in advance set content length to -1, which is also the default.

bool bufferOutput

Gets or sets if the HttpClientRequest should buffer output.

Default value is true.

__Note__: Disabling buffering of the output can result in very poor performance, when writing many small chunks.

headersgetter
HttpHeaders get headers

Returns the client request headers.

The client request headers can be modified until the client request body is written to or closed. After that they become immutable.

cookiesgetter
List<Cookie> get cookies

Cookies to present to the server (in the 'cookie' header).

donegetter
Future<HttpClientResponse> get done

An HttpClientResponse future that will complete once the response is available.

If an error occurs before the response is available, this future will complete with an error.

HttpConnectionInfo? get connectionInfo

Gets information about the client connection.

Returns null if the socket is not available.

Methods

closemethod
Future<HttpClientResponse> close()

Close the request for input. Returns the value of done.

Example
import 'raya:io';
import 'raya:convert';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async => req.response
    ..write('received ${(await utf8.decoder.bind(req).join()).length} chars')
    ..close());
  final client = HttpClient();
  final req = await client.post('127.0.0.1', server.port, '/upload');
  req.headers.contentType = ContentType.text;
  req.write('payload text');
  final res = await req.close().timeout(const Duration(seconds: 2)); // sends the body and waits for the response
  print('${res.statusCode}: ${await utf8.decoder.bind(res).join()}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
200: received 12 chars
abortmethod
void abort([Object? exception, StackTrace? stackTrace])

Aborts the client connection.

If the connection has not yet completed, the request is aborted and the done future (also returned by close) is completed with the provided exception and stackTrace. If exception is omitted, it defaults to an HttpException, and if stackTrace is omitted, it defaults to StackTrace.empty.

If the done future has already completed, aborting has no effect.

Using the IOSink methods (e.g. write and add) has no effect after the request has been aborted

var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.write('request content');
Timer(Duration(seconds: 1), () {
  request.abort();
});
request.close().then((response) {
  // If response comes back before abort, this callback will be called.
}, onError: (e) {
  // If abort() called before response is available, onError will fire.
});
Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) => req.response.close());
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/');
  req.abort(StateError('user cancelled'));
  try {
    await req.close();
  } on StateError catch (e) {
    print('close after abort: ${e.message}');
  }
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
close after abort: user cancelled
abstract interface class HttpClientResponse implements Stream<List<int>>

HTTP response for a client connection.

The body of an HttpClientResponse object is a Stream of data from the server. Use Stream methods like Stream.transform and Stream.join to access the data.

var client = HttpClient();
try {
  HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
  HttpClientResponse response = await request.close();
  final stringData = await response.transform(utf8.decoder).join();
  print(stringData);
} finally {
  client.close();
}

Properties

int get statusCode

Returns the status code.

The status code must be set before the body is written to. Setting the status code after writing to the body will throw a StateError.

String get reasonPhrase

Returns the reason phrase associated with the status code.

The reason phrase must be set before the body is written to. Setting the reason phrase after writing to the body will throw a StateError.

int get contentLength

Returns the content length of the response body. Returns -1 if the size of the response body is not known in advance.

If the content length needs to be set, it must be set before the body is written to. Setting the content length after writing to the body will throw a StateError.

HttpClientResponseCompressionState get compressionState

The compression state of the response.

This specifies whether the response bytes were compressed when they were received across the wire and whether callers will receive compressed or uncompressed bytes when they listed to this response's byte stream.

bool get persistentConnection

Gets the persistent connection state returned by the server.

If the persistent connection state needs to be set, it must be set before the body is written to. Setting the persistent connection state after writing to the body will throw a StateError.

bool get isRedirect

Returns whether the status code is one of the normal redirect codes HttpStatus.movedPermanently, HttpStatus.found, HttpStatus.movedTemporarily, HttpStatus.seeOther and HttpStatus.temporaryRedirect.

redirectsgetter
List<RedirectInfo> get redirects

Returns the series of redirects this connection has been through. The list will be empty if no redirects were followed. redirects will be updated both in the case of an automatic and a manual redirect.

headersgetter
HttpHeaders get headers

Returns the client response headers.

The client response headers are immutable.

cookiesgetter
List<Cookie> get cookies

Cookies set by the server (from the 'set-cookie' header).

X509Certificate? get certificate

Returns the certificate of the HTTPS server providing the response. Returns null if the connection is not a secure TLS or SSL connection.

HttpConnectionInfo? get connectionInfo

Gets information about the client connection. Returns null if the socket is not available.

Methods

redirectmethod
Future<HttpClientResponse> redirect([String? method, Uri? url, bool? followLoops])

Redirects this connection to a new URL. The default value for method is the method for the current request. The default value for url is the value of the HttpHeaders.locationHeader header of the current response. All body data must have been read from the current response before calling redirect.

All headers added to the request will be added to the redirection request. However, any body sent with the request will not be part of the redirection request.

If followLoops is set to true, redirect will follow the redirect, even if the URL was already visited. The default value is false.

The method will ignore HttpClientRequest.maxRedirects and will always perform the redirect.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) {
    if (req.uri.path == '/start') {
      req.response.redirect(Uri.parse('/finish'), status: HttpStatus.found);
    } else {
      req.response..write('at ${req.uri.path}')..close();
    }
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/start')..followRedirects = false;
  final first = await req.close().timeout(const Duration(seconds: 2));
  print('first response: ${first.statusCode}, isRedirect ${first.isRedirect}');
  final next = await first.redirect(); // follow it by hand
  print('after redirect: ${String.fromCharCodes(await next.expand((c) => c).toList())}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
first response: 302, isRedirect true
after redirect: at /finish
Future<Socket> detachSocket()

Detach the underlying socket from the HTTP client. When the socket is detached the HTTP client will no longer perform any operations on it.

This is normally used when an HTTP upgrade is negotiated and the communication should continue with a different protocol.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    req.response
      ..statusCode = HttpStatus.switchingProtocols
      ..headers.set('Upgrade', 'echo')
      ..headers.set('Connection', 'Upgrade');
    final s = await req.response.detachSocket();
    s.listen((d) => s..add(d)..destroy());
  });
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/')
    ..headers.set('Connection', 'Upgrade')
    ..headers.set('Upgrade', 'echo');
  final res = await req.close().timeout(t);
  final socket = await res.detachSocket(); // the connection is ours now
  socket.add([1, 2, 3]);
  print('${res.statusCode}, echoed over the raw socket: ${await socket.expand((c) => c).toList().timeout(t)}');
  socket.destroy();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
101, echoed over the raw socket: [1, 2, 3]
enum HttpClientResponseCompressionState

Enum that specifies the compression state of the byte stream of an HttpClientResponse.

The values herein allow callers to answer the following questions as they pertain to an HttpClientResponse:

  • Can the value of the response's Content-Length HTTP header be trusted?
  • Does the caller need to manually decompress the response's byte stream?

This enum is accessed via the HttpClientResponse.compressionState value.

Values

notCompressed

The body of the HTTP response was received and remains in an uncompressed state.

In this state, the value of the Content-Length HTTP header, if specified (non-negative), should match the number of bytes produced by the response's byte stream.

decompressed

The body of the HTTP response was originally compressed, but by virtue of the HttpClient.autoUncompress configuration option, it has been automatically uncompressed.

HTTP headers are not modified, so when a response has been uncompressed in this way, the value of the Content-Length HTTP header cannot be trusted, as it will contain the compressed content length, whereas the stream of bytes produced by the response will contain uncompressed bytes.

compressed

The body of the HTTP response contains compressed bytes.

In this state, the value of the Content-Length HTTP header, if specified (non-negative), should match the number of bytes produced by the response's byte stream.

If the caller wishes to manually uncompress the body of the response, it should consult the value of the Content-Encoding HTTP header to see what type of compression has been applied. See <https://tools.ietf.org/html/rfc2616#section-14.11> for more information.

abstract interface class HttpClientCredentials

Represents credentials for authentication in HttpClient.

Subtypes of HttpClientCredentials can be passed to HttpClient.addCredentials or HttpClient.addProxyCredentials.

abstract final class HttpClientBasicCredentials implements HttpClientCredentials

Represents credentials for basic authentication.

See https://datatracker.ietf.org/doc/html/rfc7617

Constructors

factory HttpClientBasicCredentials(String username, String password)
Example
import 'raya:io';

void main() {
  final creds = HttpClientBasicCredentials('ada', 's3cret');
  final client = HttpClient();
  client.addCredentials(Uri.parse('http://localhost:8080/admin'), 'admin area', creds);
  print('basic credentials registered for /admin: ${creds is HttpClientCredentials}');
  client.close();
}
Output from the Raya VM
basic credentials registered for /admin: true
abstract final class HttpClientBearerCredentials implements HttpClientCredentials

Represents credentials for bearer token authentication.

See https://datatracker.ietf.org/doc/html/rfc6750

Constructors

factory HttpClientBearerCredentials(String token)
Example
import 'raya:io';

void main() {
  final creds = HttpClientBearerCredentials('token-123');
  final client = HttpClient()..addCredentials(Uri.parse('http://localhost/api'), 'api', creds);
  print('bearer credentials registered: ${creds is HttpClientCredentials}');
  client.close();
}
Output from the Raya VM
bearer credentials registered: true
abstract final class HttpClientDigestCredentials implements HttpClientCredentials

Represents credentials for digest authentication.

Digest authentication is only supported for servers using the MD5 algorithm and quality of protection (qop) of either "none" or "auth".

See https://datatracker.ietf.org/doc/html/rfc7616

Constructors

factory HttpClientDigestCredentials(String username, String password)
Example
import 'raya:io';

void main() {
  final creds = HttpClientDigestCredentials('ada', 's3cret');
  final client = HttpClient()..addCredentials(Uri.parse('http://localhost/secure'), 'realm', creds);
  print('digest credentials registered: ${creds is HttpClientCredentials}');
  client.close();
}
Output from the Raya VM
digest credentials registered: true
abstract interface class HttpConnectionInfo

Information about an HttpRequest, HttpResponse, HttpClientRequest, or HttpClientResponse connection.

Properties

InternetAddress get remoteAddress
int get remotePort
localPortgetter
int get localPort
abstract interface class RedirectInfo

Redirect information.

Properties

int get statusCode

Returns the status code used for the redirect.

methodgetter
String get method

Returns the method used for the redirect.

locationgetter
Uri get location

Returns the location for the redirect.

class HttpException implements IOException

Constructors

HttpExceptionconstructor
const HttpException(this.message, {this.uri})
Example
import 'raya:io';

void main() {
  final e = HttpException('Connection closed before full header was received', uri: Uri.parse('http://localhost/x'));
  print('message: ${e.message}');
  print('uri: ${e.uri}');
}
Output
message: Connection closed before full header was received
uri: http://localhost/x

Properties

messagefield
final String message
urifield
final Uri? uri

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(HttpException('Bad request'));
  print(HttpException('Not found', uri: Uri.parse('http://localhost/missing')));
}
Output
HttpException: Bad request
HttpException: Not found, uri = http://localhost/missing
class RedirectException implements HttpException

Constructors

const RedirectException(this.message, this.redirects)
Example
import 'raya:io';

void main() {
  const e = RedirectException('Redirect limit exceeded', []);
  print('message: ${e.message}, redirects: ${e.redirects.length}, is HttpException: ${e is HttpException}');
}
Output
message: Redirect limit exceeded, redirects: 0, is HttpException: true

Properties

messagefield
final String message
final List<RedirectInfo> redirects
urigetter
Uri? get uri

Methods

toStringmethod
String toString()
Example
import 'raya:io';

void main() {
  print(const RedirectException('Redirect loop detected', []));
}
Output
RedirectException: Redirect loop detected
class HttpDate

Utility functions for working with dates with HTTP specific date formats.

Static

formatstaticmethod
static String format(DateTime date)

Format a date according to [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), e.g. Thu, 1 Jan 1970 00:00:00 GMT.

Example
import 'raya:io';

void main() {
  print(HttpDate.format(DateTime.utc(2026, 11, 29, 21, 30)));
  print(HttpDate.format(DateTime.utc(1999, 1, 1)));
}
Output
Sun, 29 Nov 2026 21:30:00 GMT
Fri, 01 Jan 1999 00:00:00 GMT
parsestaticmethod
static DateTime parse(String date)

Parse a date string in either of the formats [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), [RFC-850](http://tools.ietf.org/html/rfc850 "RFC-850") or ANSI C's asctime format. These formats are listed here.

  • Thu, 1 Jan 1970 00:00:00 GMT
  • Thursday, 1-Jan-1970 00:00:00 GMT
  • Thu Jan 1 00:00:00 1970

For more information see [RFC-2616 section 3.1.1](http://tools.ietf.org/html/rfc2616#section-3.3.1 "RFC-2616 section 3.1.1").

Example
import 'raya:io';

void main() {
  for (final s in ['Sun, 29 Nov 2026 21:30:00 GMT', 'Sunday, 29-Nov-26 21:30:00 GMT', 'Sun Nov 29 21:30:00 2026']) {
    print(HttpDate.parse(s).toIso8601String());
  }
}
Output
2026-11-29T21:30:00.000Z
0026-11-29T21:30:00.000Z
2026-11-29T21:30:00.000Z
abstract class HttpOverrides

This class facilitates overriding HttpClient with a mock implementation. It should be extended by another class in client code with overrides that construct a mock implementation. The implementation in this base class defaults to the actual HttpClient implementation. For example:

// An implementation of the HttpClient interface
class MyHttpClient implements HttpClient {
  MyHttpClient(SecurityContext? c);

  @override
  noSuchMethod(Invocation invocation) {
    // your implementation here
  }
}

void main() {
  HttpOverrides.runZoned(() {
    // Operations will use MyHttpClient instead of the real HttpClient
    // implementation whenever HttpClient is used.
  }, createHttpClient: (SecurityContext? c) => MyHttpClient(c));
}

Static

currentstaticgetter
static HttpOverrides? get current
globalstaticsetter
static set global(HttpOverrides? overrides)

The HttpOverrides to use in the root Zone.

These are the HttpOverrides that will be used in the root Zone, and in Zone's that do not set HttpOverrides and whose ancestors up to the root Zone do not set HttpOverrides.

Example
import 'raya:io';

final class NoProxy extends HttpOverrides {
  @override
  String findProxyFromEnvironment(Uri url, Map<String, String>? environment) => 'DIRECT';
}

void main() {
  HttpOverrides.global = NoProxy();
  print(HttpClient.findProxyFromEnvironment(Uri.parse('http://example.com'), environment: {'http_proxy': 'proxy:8080'}));
  HttpOverrides.global = null;
  print(HttpClient.findProxyFromEnvironment(Uri.parse('http://example.com'), environment: {'http_proxy': 'proxy:8080'}));
}
Output
DIRECT
PROXY proxy:8080
runZonedstaticmethod
static R runZoned<R>(R Function() body, {HttpClient Function(SecurityContext?)? createHttpClient, String Function(Uri uri, Map<String, String>? environment)? findProxyFromEnvironment})

Runs body in a fresh Zone using the provided overrides.

Example
import 'raya:io';

void main() {
  var made = 0;
  // Created outside the zone; calling HttpClient() inside the callback would recurse.
  final shared = HttpClient()..userAgent = 'shared-client';
  HttpOverrides.runZoned(() {
    print('HttpClient() inside the zone: ${HttpClient().userAgent}');
  }, createHttpClient: (context) {
    made++;
    return shared;
  });
  print('clients requested through the override: $made');
  shared.close();
}
Output from the Raya VM
HttpClient() inside the zone: shared-client
clients requested through the override: 1
static R runWithHttpOverrides<R>(R Function() body, HttpOverrides overrides)

Runs body in a fresh Zone using the overrides found in overrides.

Note that overrides should be an instance of a class that extends HttpOverrides.

Example
import 'raya:io';

final class Agent extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) => super.createHttpClient(context)..userAgent = 'raya-tests/1.0';
}

void main() {
  HttpOverrides.runWithHttpOverrides(() {
    final c = HttpClient();
    print('userAgent: ${c.userAgent}');
    c.close();
  }, Agent());
}
Output from the Raya VM
userAgent: raya-tests/1.0

Methods

HttpClient createHttpClient(SecurityContext? context)

Returns a new HttpClient using the given context.

When this override is installed, this function overrides the behavior of new HttpClient.

Example
import 'raya:io';

final class Timeouts extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) =>
      super.createHttpClient(context)..connectionTimeout = const Duration(seconds: 3);
}

void main() {
  HttpOverrides.runWithHttpOverrides(() {
    final c = HttpClient();
    print('connectionTimeout: ${c.connectionTimeout}');
    c.close();
  }, Timeouts());
}
Output from the Raya VM
connectionTimeout: 0:00:03.000000
String findProxyFromEnvironment(Uri url, Map<String, String>? environment)

Resolves the proxy server to be used for HTTP connections.

When this override is installed, this function overrides the behavior of HttpClient.findProxyFromEnvironment.

Example
import 'raya:io';

final class CorpProxy extends HttpOverrides {
  @override
  String findProxyFromEnvironment(Uri url, Map<String, String>? environment) =>
      url.host.endsWith('.internal') ? 'DIRECT' : 'PROXY proxy.corp:3128';
}

void main() {
  HttpOverrides.runWithHttpOverrides(() {
    print(HttpClient.findProxyFromEnvironment(Uri.parse('http://wiki.internal/')));
    print(HttpClient.findProxyFromEnvironment(Uri.parse('http://example.com/')));
  }, CorpProxy());
}
Output
DIRECT
PROXY proxy.corp:3128
abstract class WebSocketStatus

WebSocket status codes used when closing a WebSocket connection.

Static

static const int normalClosure = 1000
goingAwayconstant
static const int goingAway = 1001
static const int protocolError = 1002
static const int unsupportedData = 1003
reserved1004constant
static const int reserved1004 = 1004
static const int noStatusReceived = 1005
static const int abnormalClosure = 1006
static const int invalidFramePayloadData = 1007
static const int policyViolation = 1008
static const int messageTooBig = 1009
static const int missingMandatoryExtension = 1010
static const int internalServerError = 1011
reserved1015constant
static const int reserved1015 = 1015
class CompressionOptions

Options controlling compression in a WebSocket.

A CompressionOptions instance can be passed to WebSocket.connect, or used in other similar places where WebSocket compression is configured.

In most cases the default compressionDefault is sufficient, but in some situations, it might be desirable to use different compression parameters, for example to preserve memory on small devices.

Constructors

const CompressionOptions({this.clientNoContextTakeover = false, this.serverNoContextTakeover = false, this.clientMaxWindowBits, this.serverMaxWindowBits, this.enabled = true})
Example
import 'raya:io';

void main() {
  const opts = CompressionOptions(serverNoContextTakeover: true, serverMaxWindowBits: 10);
  print('enabled: ${opts.enabled}, server window bits: ${opts.serverMaxWindowBits}');
  print('disabled preset: ${CompressionOptions.compressionOff.enabled}');
}
Output
enabled: true, server window bits: 10
disabled preset: false

Static

static const CompressionOptions compressionDefault = CompressionOptions()

Default WebSocket compression configuration.

Enables compression with default window sizes and no reuse. This is the default options used by WebSocket.connect if no CompressionOptions is supplied.

  • clientNoContextTakeover: false
  • serverNoContextTakeover: false
  • clientMaxWindowBits: null (default maximal window size of 15 bits)
  • serverMaxWindowBits: null (default maximal window size of 15 bits)
static const CompressionOptions compressionOff = CompressionOptions(enabled: false)

No-compression configuration.

Disables compression when used as compression configuration for a WebSocket.

Properties

final bool clientNoContextTakeover

Whether the client will reuse its compression instances.

final bool serverNoContextTakeover

Whether the server will reuse its compression instances.

final int? clientMaxWindowBits

The maximal window size bit count requested by the client.

The windows size for the compression is always a power of two, so the number of bits precisely determines the window size.

If set to null, the client has no preference, and the compression can use up to its default maximum window size of 15 bits depending on the server's preference.

final int? serverMaxWindowBits

The maximal window size bit count requested by the server.

The windows size for the compression is always a power of two, so the number of bits precisely determines the window size.

If set to null, the server has no preference, and the compression can use up to its default maximum window size of 15 bits depending on the client's preference.

enabledfield
final bool enabled

Whether WebSocket compression is enabled.

If not enabled, the remaining fields have no effect, and the compressionOff instance can, and should, be reused instead of creating a new instance with compression disabled.

abstract class WebSocketTransformer implements StreamTransformer<HttpRequest, WebSocket>

The WebSocketTransformer provides the ability to upgrade a HttpRequest to a WebSocket connection. It supports both upgrading a single HttpRequest and upgrading a stream of HttpRequests.

To upgrade a single HttpRequest use the static upgrade method.

HttpServer server; server.listen((request) { if (...) { WebSocketTransformer.upgrade(request).then((websocket) {... }); } else { // Do normal HTTP request processing. } });

To transform a stream of HttpRequest events as it implements a stream transformer that transforms a stream of HttpRequest into a stream of WebSockets by upgrading each HttpRequest from the HTTP or HTTPS server, to the WebSocket protocol.

Server.transform(new WebSocketTransformer).listen((webSocket) =>...);

This transformer strives to implement WebSockets as specified by RFC6455.

Constructors

factory WebSocketTransformer({Function(List<String> protocols)? protocolSelector, CompressionOptions compression = CompressionOptions.compressionDefault, int maxPayloadLength = _kDefaultWebSocketMaxPayloadLength})

Create a new WebSocketTransformer.

If protocolSelector is provided, protocolSelector will be called to select what protocol to use, if any were provided by the client. protocolSelector is should return either a String or a Future completing with a String. The String must exist in the list of protocols.

If compression is provided, the WebSocket created will be configured to negotiate with the specified CompressionOptions. If none is specified then the WebSocket will be created with the default CompressionOptions.

Frames with uncompressed size exceeding maxPayloadLength will be rejected as a protocol error. The size is unlimited by default. Default value can be configured globally by setting raya.io.default.ws.max.payload.length value in compilation configuration environment.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  // Turn every request into a WebSocket.
  server.transform(WebSocketTransformer()).listen((ws) {
    ws.listen((msg) => ws..add('echo: $msg')..close());
  });
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(t);
  ws.add('hello');
  print(await ws.single.timeout(t)); // the server closes after replying
  await server.close(force: true);
}
Output from the Raya VM
echo: hello

Static

upgradestaticmethod
static Future<WebSocket> upgrade(HttpRequest request, {Function(List<String> protocols)? protocolSelector, CompressionOptions compression = CompressionOptions.compressionDefault, int maxPayloadLength = _kDefaultWebSocketMaxPayloadLength})

Upgrades an HttpRequest to a WebSocket connection. If the request is not a valid WebSocket upgrade request an HTTP response with status code 500 will be returned. Otherwise the returned future will complete with the WebSocket when the upgrade process is complete.

If protocolSelector is provided, protocolSelector will be called to select what protocol to use, if any were provided by the client. protocolSelector is should return either a String or a Future completing with a String. The String must exist in the list of protocols.

If compression is provided, the WebSocket created will be configured to negotiate with the specified CompressionOptions. If none is specified then the WebSocket will be created with the default CompressionOptions. See WebSocketTransformer for maxPayloadLength.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    if (req.uri.path == '/ws') {
      final ws = await WebSocketTransformer.upgrade(req);
      ws.add('connected to ${req.uri.path}');
      await ws.close();
    } else {
      req.response..statusCode = 404..close();
    }
  });
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}/ws').timeout(t);
  print(await ws.single.timeout(t));
  await server.close(force: true);
}
Output from the Raya VM
connected to /ws
isUpgradeRequeststaticmethod
static bool isUpgradeRequest(HttpRequest request)

Checks whether the request is a valid WebSocket upgrade request.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final isWs = WebSocketTransformer.isUpgradeRequest(req);
    print('${req.uri.path}: upgrade request = $isWs');
    if (isWs) {
      await (await WebSocketTransformer.upgrade(req)).close().timeout(const Duration(seconds: 2));
    } else {
      await req.response.close();
    }
  });
  final client = HttpClient();
  await (await client.get('127.0.0.1', server.port, '/plain')).close().timeout(const Duration(seconds: 2)).then((r) => r.drain<void>());
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}/socket').timeout(const Duration(seconds: 2));
  await ws.drain<void>();
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
/plain: upgrade request = false
/socket: upgrade request = true