dart.io


Top-Level Variables
APPEND: dynamic
GZIP: dynamic
READ: dynamic
SYSTEM_ENCODING: dynamic
WRITE: dynamic
ZLIB: dynamic
Getters and Setters
exitCode=(int status)
pid: int
stderr: IOSink
stdin: Stdin
stdout: IOSink
Functions
exit(int status): void
sleep(Duration duration): void
stdioType(dynamic object): StdioType
Classes
BytesBuilder
CertificateException
ContentType
Cookie
DetachedSocket
Directory
DirectoryException
File
FileException
FileMode
FileStat
FileSystemCreateEvent
FileSystemDeleteEvent
FileSystemEntity
FileSystemEntityType
FileSystemEvent
FileSystemModifyEvent
FileSystemMoveEvent
GZipCodec
HandshakeException
HeaderValue
HttpClient
HttpClientBasicCredentials
HttpClientCredentials
HttpClientDigestCredentials
HttpClientRequest
HttpClientResponse
HttpConnectionInfo
HttpConnectionsInfo
HttpDate
HttpException
HttpHeaders
HttpRequest
HttpResponse
HttpServer
HttpSession
HttpStatus
IOException
IOSink
InternetAddress
InternetAddressType
Link
LinkException
NetworkInterface
OSError
Options
Platform
Process
ProcessException
ProcessResult
ProcessSignal
RandomAccessFile
RawSecureServerSocket
RawSecureSocket
RawServerSocket
RawSocket
RawSocketEvent
RedirectException
RedirectInfo
SecureServerSocket
SecureSocket
ServerSocket
Socket
SocketDirection
SocketException
SocketOption
Stdin
StdioType
SystemEncoding
TlsException
WebSocket
WebSocketException
WebSocketStatus
WebSocketTransformer
X509Certificate
ZLibCodec
ZLibDecoder
ZLibEncoder

File, socket, HTTP, and other I/O support for server applications.

The IO library is used for Dart server applications, which run on a stand-alone Dart VM from the command line. This library does not work in browser based applications.

This library allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more.

Top-Level Variables

static const dynamic APPEND
static const dynamic GZIP

An instance of the default implementation of the GZipCodec.

static const dynamic READ
static const dynamic SYSTEM_ENCODING
static const dynamic WRITE
static const dynamic ZLIB

An instance of the default implementation of the ZLibCodec.

Getters and Setters

static set exitCode=(int status)

Global exit code for the Dart VM.

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

static int get pid

Returns the PID of the current process.

static IOSink get stderr
static Stdin get stdin
static IOSink get stdout

Functions

static void exit(int status)

Exit the Dart VM process immediately with the given status code.

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

static 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.

static StdioType stdioType(dynamic object)

Class BytesBuilder

Fields
isEmpty: bool
isNotEmpty: bool
length: int
Getters and Setters
isEmpty: bool
isNotEmpty: bool
length: int
Constructors
BytesBuilder()
Methods
add(List<int> bytes): void
addByte(int byte): void
clear(): void
takeBytes(): List<int>
toBytes(): List<int>

Builds a list of bytes, allowing bytes and lists of bytes to be added at the end.

Used to efficiently collect bytes and lists of bytes, using an internal buffer. Note that it's optimized for IO, using an initial buffer of 1K bytes.

Fields

final bool isEmpty
final bool isNotEmpty
final int length

Getters and Setters

bool get isEmpty

Returns true if the buffer is empty.

bool get isNotEmpty

Returns true if the buffer is empty.

int get length

The number of bytes in the builder.

Constructors

BytesBuilder()

Construct a new empty BytesBuilder.

Methods

void add(List<int> bytes)

Appends bytes to the current contents of the builder.

Each value of bytes will be bit-representation truncated to the range 0 .. 255.

void addByte(int byte)

Append byte to the current contents of the builder.

The byte will be bit-representation truncated to the range 0 .. 255.

void clear()

Clear the contents of the builder.

List<int> takeBytes()

Returns the contents of this and clears this.

The list returned is a view of the the internal buffer, limited to the length.

List<int> toBytes()

Returns a copy of the current contents of the builder.

Leaves the contents of the builder intact.


Class CertificateException extends TlsException

Constructors
CertificateException(String message, OSError osError)

An exception that happens in the handshake phase of establishing a secure network connection, when looking up or verifying a certificate.

Constructors

CertificateException(String message, OSError osError)

Abstract class ContentType implements HeaderValue

Fields
charset: String
mimeType: String
primaryType: String
subType: String
Getters and Setters
charset: String
mimeType: String
primaryType: String
subType: String
Constructors
ContentType(String primaryType, String subType, String charset, Map<String, String> parameters)
Methods
parse(String value): ContentType

Representation of a content type. An instance of ContentType is immutable.

Fields

final String charset
final String mimeType
final String primaryType
final String subType

Getters and Setters

String get charset

Gets the character set.

String get mimeType

Gets the mime-type, without any parameters.

String get primaryType

Gets the primary type.

String get subType

Gets the sub type.

Constructors

factory ContentType(String primaryType, String subType, String charset, Map<String, String> parameters)

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 and values passed in parameters will be converted to lower case.

Methods

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, sub type html and parameter charset with value utf-8.


Abstract class Cookie

Fields
domain: String
expires: DateTime
httpOnly: bool
maxAge: int
name: String
path: String
secure: bool
value: String
Constructors
Cookie(String name, String value)
Cookie.fromSetCookieValue(String value)
Methods
toString(): String

Representation of a cookie. For cookies received by the server as Cookie header values only name and value fields will be set. When building a cookie for the 'set-cookie' header in the server and when receiving cookies in the client as 'set-cookie' headers all fields can be used.

Fields

String domain

Gets and sets the domain.

DateTime expires

Gets and sets the expiry date.

bool httpOnly

Gets and sets whether this cookie is HTTP only.

int maxAge

Gets and sets the max age. A value of 0 means delete cookie now.

String name

Gets and sets the name.

String path

Gets and sets the path.

bool secure

Gets and sets whether this cookie is secure.

String value

Gets and sets the value.

Constructors

factory Cookie(String name, String value)

Creates a new cookie optionally setting the name and value.

factory Cookie.fromSetCookieValue(String value)

Creates a new cookie by parsing a header value from a 'set-cookie' header.

Methods

String toString()

Returns the formatted string representation of the cookie. The string representation can be used for for setting the Cookie or 'set-cookie' headers


Abstract class DetachedSocket

Fields
socket: Socket
unparsedData: List
Getters and Setters
socket: Socket
unparsedData: List<int>
Constructors
DetachedSocket()

When detaching a socket from either the HttpServer or the HttpClient due to a HTTP connection upgrade there might be unparsed data already read from the socket. This unparsed data together with the detached socket is returned in an instance of this class.

Fields

final Socket socket
final List unparsedData

Getters and Setters

Socket get socket
List<int> get unparsedData

Constructors

DetachedSocket()

Abstract class Directory implements FileSystemEntity

Static Fields
current: Directory
Fields
absolute: Directory
path: String
Getters and Setters
absolute: Directory
current: Directory
current=(dynamic path)
Constructors
Directory(String path)
Methods
create(dynamic recursive): Future<Directory>
createSync(dynamic recursive): void
createTemp(): Future<Directory>
createTempSync(): Directory
list(bool recursive, bool followLinks): Stream<FileSystemEntity>
listSync(bool recursive, bool followLinks): List<FileSystemEntity>
rename(String newPath): Future<Directory>
renameSync(String newPath): Directory
resolveSymbolicLinks(): Future<String>
resolveSymbolicLinksSync(): String
toString(): String

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

Static Fields

static Directory current

Fields

final Directory absolute
final String path

Gets the path of this directory.

Getters and Setters

Directory get absolute

Returns a Directory instance whose path is the absolute path to this.

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

static Directory get current

Creates a directory object pointing to the current working directory.

static set current=(dynamic path)

Sets the current working directory of the Dart process including 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 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.

Constructors

factory Directory(String path)

Creates a directory object. The path is either an absolute path, or it is a relative path which is interpreted relative to the directory in which the Dart VM was started.

Methods

Future<Directory> create(dynamic recursive)

Creates the directory with this name.

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.

void createSync(dynamic recursive)

Synchronously creates the directory with this name.

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.

Future<Directory> createTemp()

Creates a temporary directory with a name based on the current path. The path is used as a template, and additional characters are appended to it to make a unique temporary directory name. If the path is the empty string, a default system temp directory and name are used for the template.

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

Directory createTempSync()

Synchronously creates a temporary directory with a name based on the current path. The path is used as a template, and additional characters are appended to it to make a unique temporary directory name. If the path is the empty string, a default system temp directory and name are used for the template. Returns the newly created temporary directory.

Stream<FileSystemEntity> list(bool recursive, bool followLinks)

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 their type, and links to directories are recursed into. 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.

List<FileSystemEntity> listSync(bool recursive, bool followLinks)

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 their type, and links to directories are recursed into. 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.

Future<Directory> rename(String newPath)

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

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

Directory renameSync(String newPath)

Synchronously renames this directory. Returns a Directory instance for the renamed directory.

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

Future<String> resolveSymbolicLinks()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments. resolveSymbolicLinks returns a Future<String>

resolveSymbolicLinks uses the operating system's native filesystem api to resolve the path, using the realpath function on linux and Mac OS, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinks completes the returned Future with an FileException.

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

String resolveSymbolicLinksSync()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments.

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

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

String toString()

Returns a human readable string for this Directory instance.


Class DirectoryException implements IOException

Fields
message: String
osError: OSError
path: String
Constructors
DirectoryException(String message, String path, OSError osError)
Methods
toString(): String

Fields

final String message
final OSError osError
final String path

Constructors

DirectoryException(String message, String path, OSError osError)

Methods

String toString()

Returns a string representation of this object.


Abstract class File implements FileSystemEntity

Fields
absolute: File
directory: Directory
path: String
Getters and Setters
absolute: File
directory: Directory
path: String
Constructors
File(String path)
Methods
create(): Future<File>
createSync(): void
fullPath(): Future<String>
fullPathSync(): String
lastModified(): Future<DateTime>
lastModifiedSync(): DateTime
length(): Future<int>
lengthSync(): int
open(FileMode mode): Future<RandomAccessFile>
openRead(int start, int end): Stream<List<int>>
openSync(FileMode mode): RandomAccessFile
openWrite(FileMode mode, Encoding encoding): IOSink
readAsBytes(): Future<List<int>>
readAsBytesSync(): List<int>
readAsLines(Encoding encoding): Future<List<String>>
readAsLinesSync(Encoding encoding): List<String>
readAsString(Encoding encoding): Future<String>
readAsStringSync(Encoding encoding): String
rename(String newPath): Future<File>
renameSync(String newPath): File
writeAsBytes(List<int> bytes, FileMode mode): Future<File>
writeAsBytesSync(List<int> bytes, FileMode mode): void
writeAsString(String contents, FileMode mode, Encoding encoding): Future<File>
writeAsStringSync(String contents, FileMode mode, Encoding encoding): void

A reference to a file on the file system.

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 File.delete and File.deleteSync, which operate on the link.

To operate on the underlying file data there are two options:

  • Use streaming: read the contents of the file from the Stream
this.openRead()() and write to the file by writing to the IOSink this.openWrite()().
  • Open the file for random access operations using open().

Fields

final File absolute
final Directory directory
final String path

Getters and Setters

File get absolute

Returns a File instance whose path is the absolute path to this.

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

Directory get directory

Get a Directory object for the directory containing this file.

String get path

Get the path of the file.

Constructors

factory File(String path)

Create a File object.

Methods

Future<File> create()

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

Existing files are left untouched by create. Calling create on an existing file might fail if there are restrictive permissions on the file.

void createSync()

Synchronously create the file. Existing files are left untouched by createSync. Calling createSync on an existing file might fail if there are restrictive permissions on the file.

Throws a FileException if the operation fails.

@deprecated
Future<String> fullPath()

Get the canonical full path corresponding to the file path. Returns a Future<String> that completes with the path.

*FullPath is deprecated. Use absolutePath or resolveSymbolicLinks instead. FullPath will be removed the 23rd of September, 2013.*

@deprecated
String fullPathSync()

Synchronously get the canonical full path corresponding to the file path.

Throws a FileException if the operation fails.

*FullPathSync is deprecated. Use absolutePathSync or resolveSymbolicLinksSync instead. FullPathSync will be removed the 23rd of September, 2013.*

Future<DateTime> lastModified()

Get the last-modified time of the file. Returns a Future<DateTime> that completes with a DateTime object for the modification date.

DateTime lastModifiedSync()

Get the last-modified time of the file. Throws an exception if the file does not exist.

Throws a FileException if the operation fails.

Future<int> length()

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

int lengthSync()

Synchronously get the length of the file.

Throws a FileException if the operation fails.

Future<RandomAccessFile> open(FileMode mode)

Open 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.READ: open the file for reading.

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.

FileMode.APPEND: same as FileMode.WRITE except that the file is not truncated.

Stream<List<int>> openRead(int start, int end)

Create 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 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.

RandomAccessFile openSync(FileMode mode)

Synchronously open 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 FileException if the operation fails.

IOSink openWrite(FileMode mode, Encoding encoding)

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:

  • FileMode.WRITE: truncates the file to length zero.
  • FileMode.APPEND: sets the initial write position to the end
of the file.

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.

Future<List<int>> readAsBytes()

Read the entire file contents as a list of bytes. Returns a Future<List<int>> that completes with the list of bytes that is the contents of the file.

List<int> readAsBytesSync()

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

Throws a FileException if the operation fails.

Future<List<String>> readAsLines(Encoding encoding)

Read 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.

List<String> readAsLinesSync(Encoding encoding)

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

Throws a FileException if the operation fails.

Future<String> readAsString(Encoding encoding)

Read 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.

String readAsStringSync(Encoding encoding)

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

Throws a FileException if the operation fails.

Future<File> rename(String newPath)

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

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

File renameSync(String newPath)

Synchronously renames this file. Returns a File instance for the renamed file.

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

Future<File> writeAsBytes(List<int> bytes, FileMode mode)

Write 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.

void writeAsBytesSync(List<int> bytes, FileMode mode)

Synchronously write 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.

Throws a FileException if the operation fails.

Future<File> writeAsString(String contents, FileMode mode, Encoding encoding)

Write 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.

void writeAsStringSync(String contents, FileMode mode, Encoding encoding)

Synchronously write 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.

Throws a FileException if the operation fails.


Class FileException implements IOException

Fields
message: String
osError: OSError
path: String
Constructors
FileException(String message, String path, OSError osError)
Methods
toString(): String

Fields

final String message
final OSError osError
final String path

Constructors

FileException(String message, String path, OSError osError)

Methods

String toString()

Returns a string representation of this object.


Class FileMode

Static Fields
APPEND: dynamic
READ: dynamic
WRITE: dynamic

FileMode describes the modes in which a file can be opened.

Static Fields

static const dynamic APPEND
static const dynamic READ
static const dynamic WRITE

Class FileStat

Fields
accessed: DateTime
changed: DateTime
mode: int
modified: DateTime
size: int
type: FileSystemEntityType
Methods
modeString(): String
stat(String path): Future<FileStat>
statSync(String path): FileStat
toString(): String

A FileStat object represents the result of calling the POSIX stat() function on a file system object. It is an immutable object, representing the snapshotted values returned by the stat() call.

Fields

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.

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 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.

final DateTime modified

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

final int size

The size of the file system object.

final FileSystemEntityType type

The type of the object (file, directory, or link). If the call to stat() fails, the type of the returned object is NOT_FOUND.

Methods

String modeString()

Returns the mode value as a human-readable string, 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.

static Future<FileStat> stat(String path)

Asynchronously calls the operating system's stat() function on path. Returns a Future which completes with a FileStat object containing the data returned by stat(). If the call fails, completes the future with a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.

static FileStat statSync(String path)

Calls the operating system's stat() function on path. Returns a FileStat object containing the data returned by stat(). If the call fails, returns a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.

String toString()

Returns a string representation of this object.


Class FileSystemCreateEvent extends FileSystemEvent

Methods
toString(): String

File system event for newly created file system objects.

Methods

String toString()

Returns a string representation of this object.


Class FileSystemDeleteEvent extends FileSystemEvent

Methods
toString(): String

File system event for deletion of file system objects.

Methods

String toString()

Returns a string representation of this object.


Abstract class FileSystemEntity

Static Fields
isWatchSupported: bool
Fields
absolute: FileSystemEntity
isAbsolute: bool
path: String
Getters and Setters
absolute: FileSystemEntity
isAbsolute: bool
isWatchSupported: bool
path: String
Constructors
FileSystemEntity()
Methods
delete(dynamic recursive): Future<FileSystemEntity>
deleteSync(dynamic recursive): void
exists(): Future<bool>
existsSync(): bool
identical(String path1, String path2): Future<bool>
identicalSync(String path1, String path2): bool
isDirectory(String path): Future<bool>
isDirectorySync(String path): bool
isFile(String path): Future<bool>
isFileSync(String path): bool
isLink(String path): Future<bool>
isLinkSync(String path): bool
rename(String newPath): Future<FileSystemEntity>
renameSync(String newPath): FileSystemEntity
resolveSymbolicLinks(): Future<String>
resolveSymbolicLinksSync(): String
stat(): Future<FileStat>
statSync(): FileStat
type(String path, bool followLinks): Future<FileSystemEntityType>
typeSync(String path, bool followLinks): FileSystemEntityType
watch(int events, bool recursive): Stream<FileSystemEvent>

A FileSystemEntity is a common super class for File and Directory objects.

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

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

Static Fields

static final bool isWatchSupported

Fields

final FileSystemEntity absolute
final bool isAbsolute
final String path

Getters and Setters

FileSystemEntity get absolute

Returns a FileSystemEntity whose path is the absolute path to this. The type of the returned instance is the type of this.

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

bool get isAbsolute

Returns a bool indicating whether this object's path is absolute.

On Windows, a path is absolute if it starts with \\ or a drive letter between a and z (upper or lower case) followed by :\ or :/. On non-Windows, a path is absolute if it starts with /.

static bool get isWatchSupported

Test if watch is supported on the current system.

Mac OS 10.6 and below is not supported.

String get path

Constructors

FileSystemEntity()

Methods

Future<FileSystemEntity> delete(dynamic recursive)

Deletes this FileSystemEntity.

If the FileSystemEntity is a directory, and if recursive is false, the directory must be empty. Otherwise, if recursive is true, the directory and all sub-directories and files in the directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target.

If recursive is true, the FileSystemEntity is deleted even if the type of the FileSystemEntity doesn't match the content of the file system. This behavior allows delete to be used to unconditionally delete any file system object.

Returns a Future<FileSystemEntity> that completes with this FileSystemEntity when the deletion is done. If the FileSystemEntity cannot be deleted, the future completes with an exception.

void deleteSync(dynamic recursive)

Synchronously deletes this FileSystemEntity.

If the FileSystemEntity is a directory, and if recursive is false, the directory must be empty. Otherwise, if recursive is true, the directory and all sub-directories and files in the directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target.

If recursive is true, the FileSystemEntity is deleted even if the type of the FileSystemEntity doesn't match the content of the file system. This behavior allows deleteSync to be used to unconditionally delete any file system object.

Throws an exception if the FileSystemEntity cannot be deleted.

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.

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.

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.

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.

static Future<bool> isDirectory(String path)

Checks if type(path) returns FileSystemEntityType.DIRECTORY.

static bool isDirectorySync(String path)

Synchronously checks if typeSync(path) returns FileSystemEntityType.DIRECTORY.

static Future<bool> isFile(String path)

Checks if type(path) returns FileSystemEntityType.FILE.

static bool isFileSync(String path)

Synchronously checks if typeSync(path) returns FileSystemEntityType.FILE.

static Future<bool> isLink(String path)

Checks if type(path, followLinks: false) returns FileSystemEntityType.LINK.

static bool isLinkSync(String path)

Synchronously checks if typeSync(path, followLinks: false) returns FileSystemEntityType.LINK.

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.

If newPath identifies an existing entity of the same type, that entity is replaced. If newPath identifies an existing entity of a different type, the operation fails and the future completes with an exception.

FileSystemEntity renameSync(String newPath)

Synchronously renames this file system entity. Returns a FileSystemEntity instance for the renamed entity.

If newPath identifies an existing entity of the same type, that entity is replaced. If newPath identifies an existing entity of a different type, the operation fails and an exception is thrown.

Future<String> resolveSymbolicLinks()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments. resolveSymbolicLinks returns a Future<String>

resolveSymbolicLinks uses the operating system's native filesystem api to resolve the path, using the realpath function on linux and Mac OS, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinks completes the returned Future with an FileException.

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

String resolveSymbolicLinksSync()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments.

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

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

Future<FileStat> stat()

Calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.stat(this.path).

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

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

FileStat statSync()

Synchronously calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.statSync(this.path).

Returns a FileStat object containing the data returned by stat().

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

static Future<FileSystemEntityType> type(String path, bool followLinks)

Finds the type of file system object that a path points to. Returns a Future<FileSystemEntityType> that completes with the result.

FileSystemEntityType has the constant instances FILE, DIRECTORY, LINK, and NOT_FOUND. type will return LINK only if the optional named argument followLinks is false, and path points to a link. If the path does not point to a file system object, or any other error occurs in looking up the path, NOT_FOUND is returned. The only error or exception that may be put on the returned future is ArgumentError, caused by passing the wrong type of arguments to the function.

static FileSystemEntityType typeSync(String path, bool followLinks)

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

FileSystemEntityType has the constant instances FILE, DIRECTORY, LINK, and NOT_FOUND. type will return LINK only if the optional named argument followLinks is false, and path points to a link. If the path does not point to a file system object, or any other error occurs in looking up the path, NOT_FOUND is returned. The only error or exception that may be thrown is ArgumentError, caused by passing the wrong type of arguments to the function.

Stream<FileSystemEvent> watch(int events, bool recursive)

Start watch the FileSystemEntity for changes.

The implementation uses platform-depending event-based APIs for receiving file-system notifixations, thus behvaiour depends on the platform.

  • Windows: Uses ReadDirectoryChangesW. The implementation supports
only watching dirctories but supports recursive watching.
* Linux: Uses inotify. The implementation supports watching both
files and dirctories, but doesn't support recursive watching.
* Mac OS: Uses FSEvents. The implementation supports watching both
files and dirctories, and also recursive watching. Note that FSEvents
always use recursion internally, so when disabled, some events are
ignored.
The system will start listen for events once the returned Stream is being listened to, not when the call to watch is issued. Note that the returned Stream is endless. To stop the Stream, simply cancel the subscription.


Class FileSystemEntityType

Static Fields
DIRECTORY: dynamic
FILE: dynamic
LINK: dynamic
NOT_FOUND: dynamic
Methods
toString(): String

Static Fields

static const dynamic DIRECTORY
static const dynamic FILE
static const dynamic LINK
static const dynamic NOT_FOUND

Methods

String toString()

Returns a string representation of this object.


Class FileSystemEvent

Static Fields
ALL: int
CREATE: int
DELETE: int
MODIFY: int
MOVE: int
Fields
path: String
type: int

Base event class emitted by FileSystemWatcher.

Static Fields

static const int ALL = 15
static const int CREATE = 1
static const int DELETE = 4
static const int MODIFY = 2
static const int MOVE = 8

Fields

final String path

The path that triggered the event. Depending on the platform and the FileSystemEntity, the path may be relative.

final int type

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


Class FileSystemModifyEvent extends FileSystemEvent

Fields
contentChanged: bool
Methods
toString(): String

File system event for modifications of file system objects.

Fields

final bool contentChanged

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

Methods

String toString()

Returns a string representation of this object.


Class FileSystemMoveEvent extends FileSystemEvent

Fields
destination: String
Methods
toString(): String

File system event for moving of file system objects.

Fields

final String destination

If the underlaying implementation is able to identify the destination of the moved file, destination will be set. Otherwise, it will be null.

Methods

String toString()

Returns a string representation of this object.


Class GZipCodec extends Codec<List<int>, List<int>>

Fields
decoder: Converter
encoder: Converter
level: int
Getters and Setters
decoder: Converter<List<int>, List<int>>
encoder: Converter<List<int>, List<int>>
Constructors
GZipCodec(int level)

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

The difference between ZLibCodec and GZipCodec is that the GZipCodec wraps the ZLib compressed bytes in GZip frames.

Fields

final Converter decoder
final Converter encoder
final int level

The compression level of the ZLibCodec.

Getters and Setters

Converter<List<int>, List<int>> get decoder

Get a Converter for decoding GZip compressed data.

Converter<List<int>, List<int>> get encoder

Get a Converter for encoding to GZip compressed data.

Constructors

GZipCodec(int level)

The compression-level can be set in the range of 1..10, 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, but at the cost of lower compression rates.


Class HandshakeException extends TlsException

Constructors
HandshakeException(String message, OSError osError)

An exception that happens in the handshake phase of establishing a secure network connection.

Constructors

HandshakeException(String message, OSError osError)

Abstract class HeaderValue

Fields
parameters: Map
value: String
Getters and Setters
parameters: Map<String, String>
value: String
Constructors
HeaderValue(String value, Map<String, String> parameters)
Methods
parse(String value, String parameterSeparator): HeaderValue
toString(): String

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.

To build an accepts header with the value

text/plain; q=0.3, text/html
use code like this:

HttpClientRequest request = ...;
var v = new HeaderValue("text/plain", {"q": "0.3"});
request.headers.add(HttpHeaders.ACCEPT, v);
request.headers.add(HttpHeaders.ACCEPT, "text/html");
To parse the header values use the parse static method.

HttpRequest request = ...;
List<String> values = request.headers[HttpHeaders.ACCEPT];
values.forEach((value) {
  HeaderValue v = HeaderValue.parse(value);
  // Use v.value and v.parameters
});
An instance of HeaderValue is immutable.

Fields

final Map parameters
final String value

Getters and Setters

Map<String, String> get parameters

Gets the map of parameters.

This map cannot be modified. invoking any operation which would modify the map will throw UnsupportedError.

String get value

Gets the header value.

Constructors

factory HeaderValue(String value, Map<String, String> parameters)

Creates a new header value object setting the value and parameters.

Methods

static HeaderValue parse(String value, String parameterSeparator)

Creates a new header value object from parsing a header value string with both value and optional parameters.

String toString()

Returns the formatted string representation in the form:

value; parameter1=value1; parameter2=value2


Abstract class HttpClient

Static Fields
DEFAULT_HTTPS_PORT: int
DEFAULT_HTTP_PORT: int
Fields
authenticate
authenticateProxy
badCertificateCallback
findProxy
idleTimeout: Duration
userAgent: String
Getters and Setters
authenticate=( f)
authenticateProxy=( f)
badCertificateCallback=( callback)
findProxy=( f)
Constructors
HttpClient()
Methods
addCredentials(Uri url, String realm, HttpClientCredentials credentials): void
addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials): void
close(bool force): void
findProxyFromEnvironment(Uri url, Map<String, String> environment): String
get(String host, int port, String path): Future<HttpClientRequest>
getUrl(Uri url): Future<HttpClientRequest>
open(String method, String host, int port, String path): Future<HttpClientRequest>
openUrl(String method, Uri url): Future<HttpClientRequest>
post(String host, int port, String path): Future<HttpClientRequest>
postUrl(Uri url): Future<HttpClientRequest>

A client that receives content, such as web pages, from a server using the HTTP protocol.

HttpClient contains a number of methods to send a HTTP request to a HTTP server and receive a HTTP response back.

This is a two-step process, triggered by two futures. When the first future completes with a HttpClientRequest the underlying network connection has been established, but no data has yet been sent. The HTTP headers and body can be set on the request, and close is called to sent it to the server.

The second future, which is returned by close, completes with an HttpClientResponse object when the response is received from the server. This object contains the headers and body of the response.

The future for HttpClientRequest is created by methods such as getUrl() and open().

When the HTTP response is ready a HttpClientResponse object is provided which 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'll lead to a resource leaks. Consider using HttpClientResponse.drain if the body is unused.

HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
    .then((HttpClientRequest request) {
      // Prepare the request then call close on it to send it.
      return request.close();
    })
    .then((HttpClientResponse response) {
     // Process the response.
    });
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.

The HttpClient supports persistent connections and caches network connections to reuse then for multiple requests whenever possible. This means that network connections can be kept open for some time after a request have completed. Use HttpClient.close to force shut down the HttpClient object and close the idle network connections.

By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment(). To turn off the use of proxies all together set the findProxy property to null.

HttpClient client = new HttpClient();
client.findProxy = null;

Static Fields

static const int DEFAULT_HTTPS_PORT = 443
static const int DEFAULT_HTTP_PORT = 80

Fields

authenticate
authenticateProxy
badCertificateCallback
findProxy
Duration idleTimeout

Get and set the idle timeout of non-active persistent (keep-alive) connections. The default value is 15 seconds.

String userAgent

Set and get the default value of the User-Agent header for all requests generated by this HttpClient. The default value is Dart/<version> (dart:io).

If the userAgent is set to null, no default User-Agent header will be added to each request.

Getters and Setters

set authenticate=( f)

Sets the function to be called when a site is requesting authentication. The URL requested and the security realm from the server are passed in the arguments url and 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. Otherwise response processing will continue normally.

set authenticateProxy=( f)

Sets the function to be called when a proxy is requesting authentication. Information on the proxy in use and the security realm for the authentication are passed in the arguments host, port and 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.

set badCertificateCallback=( 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 an secure HTTP request if 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 the request is made, even if the value of badCertificateCallback has changed since then.

set findProxy=( f)

Sets the function used to resolve the proxy server to be used for opening a 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.

Constructors

factory HttpClient()

Methods

void addCredentials(Uri url, String realm, HttpClientCredentials credentials)

Add credentials to be used for authorizing HTTP requests.

void addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials)

Add credentials to be used for authorizing HTTP proxies.

void close(bool force)

Shutdown 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 onError callback to indicate that the client was shutdown. In both cases trying to establish a new connection after calling shutdown will throw an exception.

static String findProxyFromEnvironment(Uri url, Map<String, String> environment)

Function for resolving the proxy server to be used for a 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 = new 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 = new HttpClient();
client.findProxy = (url) {
  return HttpClient.findProxyFromEnvironment(
      url, {"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.

Future<HttpClientRequest> get(String host, int port, String path)

Opens a HTTP connection using the GET method.

The server is specified using host and port, and the path (including possible fragment and query) is specified using path.

See open for details.

Future<HttpClientRequest> getUrl(Uri url)

Opens a HTTP connection using the GET method.

The URL to use is specified in url.

See openUrl for details.

Future<HttpClientRequest> open(String method, String host, int port, String path)

Opens a HTTP connection.

The HTTP method to use is specified in method, the server is specified using host and port, and the path (including possible fragment and query) is specified using path.

The Host header for the request will be set to the value host:port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the Host header.

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.

Future<HttpClientRequest> openUrl(String method, Uri url)

Opens a 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 host:port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the Host header.

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.

Future<HttpClientRequest> post(String host, int port, String path)

Opens a HTTP connection using the POST method.

The server is specified using host and port, and the path (including possible fragment and query) is specified using path.

See open for details.

Future<HttpClientRequest> postUrl(Uri url)

Opens a HTTP connection using the POST method.

The URL to use is specified in url.

See openUrl for details.


Abstract class HttpClientBasicCredentials extends HttpClientCredentials

Constructors
HttpClientBasicCredentials(String username, String password)

Represents credentials for basic authentication.

Constructors

factory HttpClientBasicCredentials(String username, String password)

Abstract class HttpClientCredentials

Constructors
HttpClientCredentials()

Constructors

HttpClientCredentials()

Abstract class HttpClientDigestCredentials extends HttpClientCredentials

Constructors
HttpClientDigestCredentials(String username, String password)

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".

Constructors

factory HttpClientDigestCredentials(String username, String password)

Abstract class HttpClientRequest implements IOSink

Fields
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List
done: Future
followRedirects: bool
headers: HttpHeaders
maxRedirects: int
method: String
persistentConnection: bool
uri: Uri
Getters and Setters
connectionInfo: HttpConnectionInfo
cookies: List<Cookie>
done: Future<HttpClientResponse>
headers: HttpHeaders
method: String
uri: Uri
Constructors
HttpClientRequest()
Methods
close(): Future<HttpClientResponse>

HTTP request for a client connection.

This object has a number of properties for setting up the HTTP header of the request. When the header has been set up the methods from the IOSink can be used to write the actual body of the HTTP request. When one of the IOSink methods is used for the first time the request header is send. Calling any methods that will change the header after it is sent will throw an exception.

When writing string data through the IOSink the encoding used will be determined from the "charset" parameter of the "Content-Type" header.

HttpClientRequest request = ...
request.headers.contentType
    = new ContentType("application", "json", charset: "utf-8");
request.write(...);  // Strings written will be UTF-8 encoded.
If no charset is provided the default of ISO-8859-1 (Latin 1) will be used.

HttpClientRequest request = ...
request.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
request.write(...);  // Strings written will be ISO-8859-1 encoded.
If an unsupported encoding is used an exception will be thrown if using one of the write methods taking a string.

Fields

final HttpConnectionInfo connectionInfo
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.

final List cookies
final Future done
bool followRedirects

Set this property to true if this request should automatically follow redirects. The default is true.

Automatic redirect will only happen for "GET" and "HEAD" requests and only for the status codes HttpHeaders.MOVED_PERMANENTLY (301), HttpStatus.FOUND (302), HttpStatus.MOVED_TEMPORARILY (302, alias for HttpStatus.FOUND), HttpStatus.SEE_OTHER (303) and HttpStatus.TEMPORARY_REDIRECT (307). For HttpStatus.SEE_OTHER (303) autmatic 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). However, any body send with the request will not be part of the redirection request(s).

final HttpHeaders headers
int maxRedirects

Set this property to the maximum number of redirects to follow when followRedirects is true. If this number is exceeded the onError callback will be called with a RedirectException.

The default value is 5.

final String method
bool persistentConnection

Gets and sets the requested persistent connection state. The default value is true.

final Uri uri

Getters and Setters

HttpConnectionInfo get connectionInfo

Get information about the client connection. Returns null if the socket is not available.

List<Cookie> get cookies

Cookies to present to the server (in the 'cookie' header).

Future<HttpClientResponse> get done

A 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.

HttpHeaders get headers

Returns the request headers.

String get method

The method of the request.

Uri get uri

The uri of the request.

Constructors

HttpClientRequest()

Methods

Future<HttpClientResponse> close()

Close the request for input. Returns the value of done.


Abstract class HttpClientResponse implements Stream<List<int>>

Fields
certificate: X509Certificate
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List
headers: HttpHeaders
isRedirect: bool
persistentConnection: bool
reasonPhrase: String
redirects: List
statusCode: int
Getters and Setters
certificate: X509Certificate
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List<Cookie>
headers: HttpHeaders
isRedirect: bool
persistentConnection: bool
reasonPhrase: String
redirects: List<RedirectInfo>
statusCode: int
Constructors
HttpClientResponse()
Methods
detachSocket(): Future<Socket>
redirect(String method, Uri url, bool followLoops): Future<HttpClientResponse>

HTTP response for a client connection. The HttpClientResponse is a Stream of the body content of the response. Listen to the body to handle the data and be notified once the entire body is received.

Fields

final X509Certificate certificate
final HttpConnectionInfo connectionInfo
final int contentLength
final List cookies
final HttpHeaders headers
final bool isRedirect
final bool persistentConnection
final String reasonPhrase
final List redirects
final int statusCode

Getters and Setters

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.

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.

List<Cookie> get cookies

Cookies set by the server (from the 'set-cookie' header).

HttpHeaders get headers

Returns the response headers.

bool get isRedirect

Returns whether the status code is one of the normal redirect codes HttpStatus.MOVED_PERMANENTLY, HttpStatus.FOUND, HttpStatus.MOVED_TEMPORARILY, HttpStatus.SEE_OTHER and HttpStatus.TEMPORARY_REDIRECT.

bool get persistentConnection

Gets the persistent connection state returned by the server.

String get reasonPhrase

Returns the reason phrase associated with the status code.

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.

int get statusCode

Returns the status code.

Constructors

HttpClientResponse()

Methods

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 a HTTP upgrade is negotiated and the communication should continue with a different protocol.

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.LOCATION 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.

redirect will ignore maxRedirects and will always perform the redirect.


Abstract class HttpConnectionInfo

Fields
localPort: int
remoteHost: String
remotePort: int
Getters and Setters
localPort: int
remoteHost: String
remotePort: int
Constructors
HttpConnectionInfo()

Information about an HttpRequest, HttpResponse, HttpClientRequest, or HttpClientResponse connection.

Fields

final int localPort
final String remoteHost
final int remotePort

Getters and Setters

int get localPort
String get remoteHost
int get remotePort

Constructors

HttpConnectionInfo()

Class HttpConnectionsInfo

Fields
active: int
closing: int
idle: int
total: int
Constructors
HttpConnectionsInfo()

Summary statistics about an HttpServers current socket connections.

Fields

int active

Number of active connections where actual request/response processing is active.

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.

int idle

Number of idle connections held by clients as persistent connections.

int total

Total number of socket connections.

Constructors

HttpConnectionsInfo()

Class HttpDate

Constructors
HttpDate()
Methods
format(DateTime date): String
parse(String date): DateTime

Utility functions for working with dates with HTTP specific date formats.

Constructors

HttpDate()

Methods

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.

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").


Class HttpException implements IOException

Fields
message: String
uri: Uri
Constructors
HttpException(String message, Uri uri)
Methods
toString(): String

Fields

final String message
final Uri uri

Constructors

HttpException(String message, Uri uri)

Methods

String toString()

Returns a string representation of this object.


Abstract class HttpHeaders

Static Fields
ACCEPT: dynamic
ACCEPT_CHARSET: dynamic
ACCEPT_ENCODING: dynamic
ACCEPT_LANGUAGE: dynamic
ACCEPT_RANGES: dynamic
AGE: dynamic
ALLOW: dynamic
AUTHORIZATION: dynamic
CACHE_CONTROL: dynamic
CONNECTION: dynamic
CONTENT_ENCODING: dynamic
CONTENT_LANGUAGE: dynamic
CONTENT_LENGTH: dynamic
CONTENT_LOCATION: dynamic
CONTENT_MD5: dynamic
CONTENT_RANGE: dynamic
CONTENT_TYPE: dynamic
COOKIE: dynamic
DATE: dynamic
ENTITY_HEADERS: dynamic
ETAG: dynamic
EXPECT: dynamic
EXPIRES: dynamic
FROM: dynamic
GENERAL_HEADERS: dynamic
HOST: dynamic
IF_MATCH: dynamic
IF_MODIFIED_SINCE: dynamic
IF_NONE_MATCH: dynamic
IF_RANGE: dynamic
IF_UNMODIFIED_SINCE: dynamic
LAST_MODIFIED: dynamic
LOCATION: dynamic
MAX_FORWARDS: dynamic
PRAGMA: dynamic
PROXY_AUTHENTICATE: dynamic
PROXY_AUTHORIZATION: dynamic
RANGE: dynamic
REFERER: dynamic
REQUEST_HEADERS: dynamic
RESPONSE_HEADERS: dynamic
RETRY_AFTER: dynamic
SERVER: dynamic
SET_COOKIE: dynamic
TE: dynamic
TRAILER: dynamic
TRANSFER_ENCODING: dynamic
UPGRADE: dynamic
USER_AGENT: dynamic
VARY: dynamic
VIA: dynamic
WARNING: dynamic
WWW_AUTHENTICATE: dynamic
Fields
chunkedTransferEncoding: bool
contentLength: int
contentType: ContentType
date: DateTime
expires: DateTime
host: String
ifModifiedSince: DateTime
persistentConnection: bool
port: int
Constructors
HttpHeaders()
Methods
[](String name): List<String>
add(String name, Object value): void
forEach( f): void
noFolding(String name): void
remove(String name, Object value): void
removeAll(String name): void
set(String name, Object value): void
value(String name): String

Access to the HTTP headers for requests and responses. In some situations the headers will be immutable and the mutating methods will then throw exceptions.

For all operations on HTTP headers the header name is case-insensitive.

Static Fields

static const dynamic ACCEPT = 'accept'
static const dynamic ACCEPT_CHARSET = 'accept-charset'
static const dynamic ACCEPT_ENCODING = 'accept-encoding'
static const dynamic ACCEPT_LANGUAGE = 'accept-language'
static const dynamic ACCEPT_RANGES = 'accept-ranges'
static const dynamic AGE = 'age'
static const dynamic ALLOW = 'allow'
static const dynamic AUTHORIZATION = 'authorization'
static const dynamic CACHE_CONTROL = 'cache-control'
static const dynamic CONNECTION = 'connection'
static const dynamic CONTENT_ENCODING = 'content-encoding'
static const dynamic CONTENT_LANGUAGE = 'content-language'
static const dynamic CONTENT_LENGTH = 'content-length'
static const dynamic CONTENT_LOCATION = 'content-location'
static const dynamic CONTENT_MD5 = 'content-md5'
static const dynamic CONTENT_RANGE = 'content-range'
static const dynamic CONTENT_TYPE = 'content-type'
static const dynamic COOKIE = 'cookie'
static const dynamic DATE = 'date'
static const dynamic ENTITY_HEADERS
static const dynamic ETAG = 'etag'
static const dynamic EXPECT = 'expect'
static const dynamic EXPIRES = 'expires'
static const dynamic FROM = 'from'
static const dynamic GENERAL_HEADERS
static const dynamic HOST = 'host'
static const dynamic IF_MATCH = 'if-match'
static const dynamic IF_MODIFIED_SINCE = 'if-modified-since'
static const dynamic IF_NONE_MATCH = 'if-none-match'
static const dynamic IF_RANGE = 'if-range'
static const dynamic IF_UNMODIFIED_SINCE = 'if-unmodified-since'
static const dynamic LAST_MODIFIED = 'last-modified'
static const dynamic LOCATION = 'location'
static const dynamic MAX_FORWARDS = 'max-forwards'
static const dynamic PRAGMA = 'pragma'
static const dynamic PROXY_AUTHENTICATE = 'proxy-authenticate'
static const dynamic PROXY_AUTHORIZATION = 'proxy-authorization'
static const dynamic RANGE = 'range'
static const dynamic REFERER = 'referer'
static const dynamic REQUEST_HEADERS
static const dynamic RESPONSE_HEADERS
static const dynamic RETRY_AFTER = 'retry-after'
static const dynamic SERVER = 'server'
static const dynamic SET_COOKIE = 'set-cookie'
static const dynamic TE = 'te'
static const dynamic TRAILER = 'trailer'
static const dynamic TRANSFER_ENCODING = 'transfer-encoding'
static const dynamic UPGRADE = 'upgrade'
static const dynamic USER_AGENT = 'user-agent'
static const dynamic VARY = 'vary'
static const dynamic VIA = 'via'
static const dynamic WARNING = 'warning'
static const dynamic WWW_AUTHENTICATE = 'www-authenticate'

Fields

bool chunkedTransferEncoding

Gets and sets the chunked transfer encoding header value.

int contentLength

Gets and sets the content length header value.

ContentType contentType

Gets and sets the content type. Note that the content type in the header will only be updated if this field is set directly. Mutating the returned current value will have no effect.

DateTime date

Gets and sets the date. The value of this property will reflect the 'date' header.

DateTime expires

Gets and sets the expiry date. The value of this property will reflect the 'expires' header.

String host

Gets and sets the host part of the 'host' header for the connection.

DateTime ifModifiedSince

Gets and sets the "if-modified-since" date. The value of this property will reflect the "if-modified-since" header.

bool persistentConnection

Gets and sets the persistent connection header value.

int port

Gets and sets the port part of the 'host' header for the connection.

Constructors

HttpHeaders()

Methods

List<String> [](String name)

Returns the list of values for the header named name. If there is no header with the provided name, null will be returned.

void add(String name, Object value)

Adds a header value. The header named name will have the value value added to its list of values. Some headers are single valued, and for these adding a value will replace the previous value. If the value is of type DateTime a HTTP date format will be applied. If the value is a List each element of the list will be added separately. For all other types the default toString method will be used.

void forEach( f)

Enumerates the headers, applying the function f to each header. The header name passed in name will be all lower case.

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.

void remove(String name, Object value)

Removes a specific value for a header name. Some headers have system supplied values and for these the system supplied values will still be added to the collection of values for the header.

void removeAll(String name)

Removes all values for the specified header name. Some headers have system supplied values and for these the system supplied values will still be added to the collection of values for the header.

void set(String name, Object value)

Sets a header. The header named name will have all its values cleared before the value value is added as its value.

String value(String name)

Convenience method for the value for a single valued header. If there is no header with the provided name, null will be returned. If the header has more than one value an exception is thrown.


Abstract class HttpRequest implements Stream<List<int>>

Fields
certificate: X509Certificate
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List
headers: HttpHeaders
method: String
persistentConnection: bool
protocolVersion: String
response: HttpResponse
session: HttpSession
uri: Uri
Getters and Setters
certificate: X509Certificate
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List<Cookie>
headers: HttpHeaders
method: String
persistentConnection: bool
protocolVersion: String
response: HttpResponse
session: HttpSession
uri: Uri
Constructors
HttpRequest()

A server-side object that contains the content of and information about an HTTP request.

Note: Check out the http_server(http://pub.dartlang.org/packages/http_server) package, which makes working with the low-level dart:io HTTP server subsystem easier.

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 bytes. 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 and, within the callback function, uses the HttpRequest object's method property to dispatch requests.

final HOST = InternetAddress.LOOPBACK_IP_V4;
final PORT = 4040;

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);
  
Listen to the HttpRequest stream to handle the data and be notified once the entire body is received. An HttpRequest object contains an HttpResponse object, to which the server can write its response. For example, here's a skeletal callback function that responds to a request:

void handleGetRequest(HttpRequest req) {
  HttpResponse res = req.response;
  var body = [];
  req.listen((List<int> buffer) => body.add(buffer),
    onDone: () {
      res.write('Received ${body.length} for request ');
      res.write(' ${req.method}: ${req.uri.path}');
      res.close();
    },
    onError: handleError);
}

Fields

final X509Certificate certificate
final HttpConnectionInfo connectionInfo
final int contentLength
final List cookies
final HttpHeaders headers
final String method
final bool persistentConnection
final String protocolVersion
final HttpResponse response
final HttpSession session
final Uri uri

Getters and Setters

X509Certificate get certificate

The client certificate of the client making the request (read-only).

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.

HttpConnectionInfo get connectionInfo

Information about the client connection (read-only).

Returns null if the socket is not available.

int get contentLength

The content length of the request body (read-only).

If the size of the request body is not known in advance, this value is -1.

List<Cookie> get cookies

The cookies in the request, from the Cookie headers (read-only).

HttpHeaders get headers

The request headers (read-only).

String get method

The method, such as 'GET' or 'POST', for the request (read-only).

bool get persistentConnection

The persistent connection state signaled by the client (read-only).

String get protocolVersion

The HTTP protocol version used in the request, either "1.0" or "1.1" (read-only).

HttpResponse get response

The HttpResponse object, used for sending back the response to the client (read-only).

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.

HttpSession get session

The session for the given request (read-only).

If the session is being initialized by this call, isNew is true for the returned session. See HttpServer.sessionTimeout on how to change default timeout.

Uri get uri

The URI for the request (read-only).

This provides access to the path, query string, and fragment identifier for the request.

Constructors

HttpRequest()

Abstract class HttpResponse implements IOSink

Fields
connectionInfo: HttpConnectionInfo
contentLength: int
cookies: List
deadline: Duration
headers: HttpHeaders
persistentConnection: bool
reasonPhrase: String
statusCode: int
Getters and Setters
connectionInfo: HttpConnectionInfo
cookies: List<Cookie>
headers: HttpHeaders
Constructors
HttpResponse()
Methods
detachSocket(): Future<Socket>
redirect(Uri location, int status): Future<dynamic>

An HttpResponse represents the headers and data to be returned to a client in response to an HTTP request.

This object has a number of properties for setting up the HTTP header of the response. When the header has been set up the methods from the IOSink can be used to write the actual body of the HTTP response. When one of the IOSink methods is used for the first time the request header is send. Calling any methods that will change the header after it is sent will throw an exception.

When writing string data through the IOSink the encoding used will be determined from the "charset" parameter of the "Content-Type" header.

HttpResponse response = ...
response.headers.contentType
    = new 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.CONTENT_TYPE, "text/plain");
response.write(...);  // Strings written will be ISO-8859-1 encoded.
If an unsupported encoding is used an exception will be thrown if using one of the write methods taking a string.

Fields

final HttpConnectionInfo connectionInfo
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.

final List cookies
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.

final HttpHeaders headers
bool persistentConnection

Gets and sets the persistent connection state. The initial value of this property is the persistent connection state from the request.

String reasonPhrase

Gets and sets the reason phrase. If no reason phrase is explicitly set a default reason phrase is provided.

int statusCode

Gets and sets the status code. 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.

Getters and Setters

HttpConnectionInfo get connectionInfo

Gets information about the client connection. Returns null if the socket is not available.

List<Cookie> get cookies

Cookies to set in the client (in the 'set-cookie' header).

HttpHeaders get headers

Returns the response headers.

Constructors

HttpResponse()

Methods

Future<Socket> detachSocket()

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 a HTTP upgrade request is received and the communication should continue with a different protocol.

Future<dynamic> redirect(Uri location, int status)

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.MOVED_TEMPORARILY (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 furure returned by close.


Abstract class HttpServer implements Stream<HttpRequest>

Fields
idleTimeout: Duration
port: int
serverHeader: String
sessionTimeout: int
Getters and Setters
port: int
sessionTimeout=(int timeout)
Constructors
HttpServer.listenOn(ServerSocket serverSocket)
Methods
bind(dynamic address, int port, int backlog): Future<HttpServer>
bindSecure(dynamic address, int port, int backlog, String certificateName, bool requestClientCertificate): Future<HttpServer>
close(): Future<dynamic>
connectionsInfo(): HttpConnectionsInfo

A server that delivers content, such as web pages, using the HTTP protocol.

The HttpServer is a Stream of HttpRequests. Each HttpRequest has an associated HttpResponse object as its HttpRequest.response member, and the server responds to a request by writing to that HttpResponse object.

Incomplete requests where all or parts of the header is missing, are ignored and no exceptions or HttpRequest objects are generated for them. Likewise, when writing to a 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'll be drained when the HttpResponse is being written to or closed.

The following example shows how to bind a HttpServer to a IPv6 InternetAddress on port 80, and listening to requests.

HttpServer.bind(InternetAddress.ANY_IP_V6, 80).then((server) {

server.listen((HttpRequest request) {
  // Handle requests.
});
});

Fields

Duration idleTimeout

Get or set 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 droped.

Default is 120 seconds.

To disable, set idleTimeout to null.

final int port
String serverHeader

Set and get the default value of the Server header for all responses generated by this HttpServer. The default value is Dart/<version> (dart:io).

If the serverHeader is set to null, no default Server header will be added to each response.

int sessionTimeout

Getters and Setters

int get port

Returns the port that the server is listening on. This can be used to get the actual port used when a value of 0 for port is specified in the bind or bindSecure call.

set sessionTimeout=(int timeout)

Sets the timeout, in seconds, for sessions of this HttpServer. The default timeout is 20 minutes.

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.

Methods

static Future<HttpServer> bind(dynamic address, int port, int backlog)

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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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 HttpServer.listenOn with a ServerSocket configured for IP version 6 connections 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.

static Future<HttpServer> bindSecure(dynamic address, int port, int backlog, String certificateName, bool requestClientCertificate)

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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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 HttpServer.listenOn with a ServerSocket configured for IP version 6 connections 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 certificate with nickname or distinguished name (DN) certificateName is looked up in the certificate database, and is used as the server certificate. If requestClientCertificate is true, the server will request clients to authenticate with a client certificate.

Future<dynamic> close()

Permanently stops this HttpServer from listening for new connections. This closes this 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.

HttpConnectionsInfo connectionsInfo()

Returns an HttpConnectionsInfo object summarizing the number of current connections handled by the server.


Abstract class HttpSession implements Map<dynamic, dynamic>

Fields
id: String
isNew: bool
onTimeout
Getters and Setters
id: String
isNew: bool
onTimeout=( callback)
Constructors
HttpSession()
Methods
destroy(): void

Fields

final String id
final bool isNew
onTimeout

Getters and Setters

String get id

Gets the id for the current session.

bool get isNew

Is true if the session has not been sent to the client yet.

set onTimeout=( callback)

Sets a callback that will be called when the session is timed out.

Constructors

HttpSession()

Methods

void destroy()

Destroys the session. This will terminate the session and any further connections with this id will be given a new id and session.


Abstract class HttpStatus

Static Fields
ACCEPTED: int
BAD_GATEWAY: int
BAD_REQUEST: int
CONFLICT: int
CONTINUE: int
CREATED: int
EXPECTATION_FAILED: int
FORBIDDEN: int
FOUND: int
GATEWAY_TIMEOUT: int
GONE: int
HTTP_VERSION_NOT_SUPPORTED: int
INTERNAL_SERVER_ERROR: int
LENGTH_REQUIRED: int
METHOD_NOT_ALLOWED: int
MOVED_PERMANENTLY: int
MOVED_TEMPORARILY: int
MULTIPLE_CHOICES: int
NETWORK_CONNECT_TIMEOUT_ERROR: int
NON_AUTHORITATIVE_INFORMATION: int
NOT_ACCEPTABLE: int
NOT_FOUND: int
NOT_IMPLEMENTED: int
NOT_MODIFIED: int
NO_CONTENT: int
OK: int
PARTIAL_CONTENT: int
PAYMENT_REQUIRED: int
PRECONDITION_FAILED: int
PROXY_AUTHENTICATION_REQUIRED: int
REQUESTED_RANGE_NOT_SATISFIABLE: int
REQUEST_ENTITY_TOO_LARGE: int
REQUEST_TIMEOUT: int
REQUEST_URI_TOO_LONG: int
RESET_CONTENT: int
SEE_OTHER: int
SERVICE_UNAVAILABLE: int
SWITCHING_PROTOCOLS: int
TEMPORARY_REDIRECT: int
UNAUTHORIZED: int
UNSUPPORTED_MEDIA_TYPE: int
USE_PROXY: int
Constructors
HttpStatus()

HTTP status codes.

Static Fields

static const int ACCEPTED = 202
static const int BAD_GATEWAY = 502
static const int BAD_REQUEST = 400
static const int CONFLICT = 409
static const int CONTINUE = 100
static const int CREATED = 201
static const int EXPECTATION_FAILED = 417
static const int FORBIDDEN = 403
static const int FOUND = 302
static const int GATEWAY_TIMEOUT = 504
static const int GONE = 410
static const int HTTP_VERSION_NOT_SUPPORTED = 505
static const int INTERNAL_SERVER_ERROR = 500
static const int LENGTH_REQUIRED = 411
static const int METHOD_NOT_ALLOWED = 405
static const int MOVED_PERMANENTLY = 301
static const int MOVED_TEMPORARILY = 302
static const int MULTIPLE_CHOICES = 300
static const int NETWORK_CONNECT_TIMEOUT_ERROR = 599
static const int NON_AUTHORITATIVE_INFORMATION = 203
static const int NOT_ACCEPTABLE = 406
static const int NOT_FOUND = 404
static const int NOT_IMPLEMENTED = 501
static const int NOT_MODIFIED = 304
static const int NO_CONTENT = 204
static const int OK = 200
static const int PARTIAL_CONTENT = 206
static const int PAYMENT_REQUIRED = 402
static const int PRECONDITION_FAILED = 412
static const int PROXY_AUTHENTICATION_REQUIRED = 407
static const int REQUESTED_RANGE_NOT_SATISFIABLE = 416
static const int REQUEST_ENTITY_TOO_LARGE = 413
static const int REQUEST_TIMEOUT = 408
static const int REQUEST_URI_TOO_LONG = 414
static const int RESET_CONTENT = 205
static const int SEE_OTHER = 303
static const int SERVICE_UNAVAILABLE = 503
static const int SWITCHING_PROTOCOLS = 101
static const int TEMPORARY_REDIRECT = 307
static const int UNAUTHORIZED = 401
static const int UNSUPPORTED_MEDIA_TYPE = 415
static const int USE_PROXY = 305

Constructors

HttpStatus()

Abstract class IOException implements Exception

Constructors
IOException()
Methods
toString(): String

Base class for all IO related exceptions.

Constructors

IOException()

Methods

String toString()

Returns a string representation of this object.


Abstract class IOSink implements StreamSink<List<int>>, StringSink

Fields
done: Future
encoding: Encoding
Getters and Setters
done: Future<dynamic>
Constructors
IOSink(StreamConsumer<List<int>> target, Encoding encoding)
Methods
add(List<int> data): void
addError(dynamic error): void
addStream(Stream<List<int>> stream): Future<dynamic>
close(): Future<dynamic>

Helper class to wrap a StreamConsumer<List<int>> and provide utility functions for writing to the StreamConsumer directly. The IOSink buffers the input given by all StringSink methods and will delay a addStream() until the buffer is flushed.

When the IOSink is bound to a stream (through addStream()) any call to the IOSink will throw a StateError. When the addStream() completes, the IOSink will again be open for all calls.

If data is added to the IOSink after the sink is closed, the data will be ignored. Use the done future to be notified when the IOSink is closed.

Fields

final Future done
Encoding encoding

The Encoding used when writing strings. Depending on the underlying consumer this property might be mutable.

Getters and Setters

Future<dynamic> get done

Get a future that will complete when all synchronous have completed, or an error happened. This future is identical to the future returned from close.

Constructors

factory IOSink(StreamConsumer<List<int>> target, Encoding encoding)

Methods

void add(List<int> data)

Writes the bytes uninterpreted to the consumer. While the call is synchronous, the data may be buffered until the underlying resource is ready. The data should not be modified after a call to add.

void addError(dynamic error)

Writes an error to the consumer.

Future<dynamic> addStream(Stream<List<int>> stream)

Adds all elements of the given stream to this.

Future<dynamic> close()

Close the target.


Abstract class InternetAddress

Static Fields
ANY_IP_V4: InternetAddress
ANY_IP_V6: InternetAddress
LOOPBACK_IP_V4: InternetAddress
LOOPBACK_IP_V6: InternetAddress
Fields
address: String
host: String
isLinkLocal: bool
isLoopback: bool
type: InternetAddressType
Getters and Setters
ANY_IP_V4: InternetAddress
ANY_IP_V6: InternetAddress
LOOPBACK_IP_V4: InternetAddress
LOOPBACK_IP_V6: InternetAddress
address: String
host: String
isLinkLocal: bool
isLoopback: bool
Constructors
InternetAddress()
Methods
lookup(String host, InternetAddressType type): Future<List<InternetAddress>>
reverse(): Future<InternetAddress>

The InternetAddress is an object reflecting either a remote or a local address. When combined with a port number, this represents a endpoint that a socket can connect to or a listening socket can bind to.

Static Fields

static final InternetAddress ANY_IP_V4
static final InternetAddress ANY_IP_V6
static final InternetAddress LOOPBACK_IP_V4
static final InternetAddress LOOPBACK_IP_V6

Fields

final String address
final String host
final bool isLinkLocal
final bool isLoopback
InternetAddressType type

The type of the InternetAddress specified what IP protocol.

Getters and Setters

static InternetAddress get ANY_IP_V4

IP version 4 any address. Use this address when listening on all adapters IP addresses using IP version 4 (IPv4).

static InternetAddress get ANY_IP_V6

IP version 6 any address. Use this address when listening on all adapters IP addresses using IP version 6 (IPv6).

static InternetAddress get LOOPBACK_IP_V4

IP version 4 loopback address. Use this address when listening on or connecting to the loopback adapter using IP version 4 (IPv4).

static InternetAddress get LOOPBACK_IP_V6

IP version 6 loopback address. Use this address when listening on or connecting to the loopback adapter using IP version 6 (IPv6).

String get address

The resolved address of the host.

String get host

The host used to lookup the address.

bool get isLinkLocal

Returns true if the InternetAddresss scope is a link-local.

bool get isLoopback

Returns true if the InternetAddress is a loopback address.

Constructors

InternetAddress()

Methods

static Future<List<InternetAddress>> lookup(String host, InternetAddressType type)

Lookup a host, returning a Future of a list of InternetAddresss. If type is InternetAddressType.ANY, it will lookup both IP version 4 (IPv4) and IP version 6 (IPv6) addresses. If type is either InternetAddressType.IP_V4 or InternetAddressType.IP_V6 it will only lookup addresses of the specified type. The order of the list can, and most likely will, change over time.

Future<InternetAddress> reverse()

Perform a reverse dns lookup on the address, creating a new InternetAddress where the host field set to the result.


Class InternetAddressType

Static Fields
ANY: InternetAddressType
IP_V4: InternetAddressType
IP_V6: InternetAddressType
Fields
name: String
Getters and Setters
name: String
Methods
toString(): String

InternetAddressType is the type an InternetAddress. Currently, IP version 4 (IPv4) and IP version 6 (IPv6) are supported.

Static Fields

static const InternetAddressType ANY
static const InternetAddressType IP_V4
static const InternetAddressType IP_V6

Fields

final String name

Getters and Setters

String get name

Get the name of the type, e.g. "IP_V4" or "IP_V6".

Methods

String toString()

Returns a string representation of this object.


Abstract class Link implements FileSystemEntity

Fields
absolute: Link
Getters and Setters
absolute: Link
Constructors
Link(String path)
Methods
create(String target): Future<Link>
createSync(String target): void
rename(String newPath): Future<Link>
renameSync(String newPath): Link
resolveSymbolicLinks(): Future<String>
resolveSymbolicLinksSync(): String
target(): Future<String>
targetSync(): String
update(String target): Future<Link>
updateSync(String target): void

Link objects are references to filesystem links.

Fields

final Link absolute

Getters and Setters

Link get absolute

Returns a Link instance whose path is the absolute path to this.

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

Constructors

factory Link(String path)

Creates a Link object.

Methods

Future<Link> create(String target)

Creates a symbolic link. Returns a Future<Link> that completes with the link when it has been created. If the link exists, the future will complete with an error.

On the Windows platform, this will only work with directories, and the target directory must exist. The link will be created as a Junction. Only absolute links will be created, and relative paths to the target will be converted to absolute paths by joining them with the path of the directory the link is contained in.

On other platforms, the posix symlink() call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.

void createSync(String target)

Synchronously create the link. Calling createSync on an existing link will throw an exception.

On the Windows platform, this will only work with directories, and the target directory must exist. The link will be created as a Junction. Only absolute links will be created, and relative paths to the target will be converted to absolute paths.

On other platforms, the posix symlink() call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.

Future<Link> rename(String newPath)

Renames this link. Returns a Future<Link> that completes with a Link instance for the renamed link.

If newPath identifies an existing link, that link is replaced. If newPath identifies an existing file or directory, the operation fails and the future completes with an exception.

Link renameSync(String newPath)

Synchronously renames this link. Returns a Link instance for the renamed link.

If newPath identifies an existing link, that link is replaced. If newPath identifies an existing file or directory the operation fails and an exception is thrown.

Future<String> resolveSymbolicLinks()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments. resolveSymbolicLinks returns a Future<String>

resolveSymbolicLinks uses the operating system's native filesystem api to resolve the path, using the realpath function on linux and Mac OS, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinks completes the returned Future with an FileException.

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

String resolveSymbolicLinksSync()

Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all '..' and '.' path segments.

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

On Windows, symbolic links are resolved to their target before applying a '..' that follows, and on other platforms, the '..' is applied to the symbolic link without resolving it. The second behavior can be emulated on Windows by processing any '..' segments before calling resolveSymbolicLinks. One way of doing this is with the URI class: :new Uri.parse('.').resolveUri(new Uri.file(input)).toFilePath();, since resolve removes '..' segments.

Future<String> target()

Gets the target of the link. Returns a future that completes with the path to the target.

If the returned target is a relative path, it is relative to the directory containing the link.

If the link does not exist, or is not a link, the future completes with a LinkException.

String targetSync()

Synchronously gets the target of the link. Returns the path to the target.

If the returned target is a relative path, it is relative to the directory containing the link.

If the link does not exist, or is not a link, throws a LinkException.

Future<Link> update(String target)

Updates the link. Returns a Future<Link> that completes with the link when it has been updated. Calling update on a non-existing link will complete its returned future with an exception.

On the Windows platform, this will only work with directories, and the target directory must exist.

void updateSync(String target)

Synchronously updates the link. Calling updateSync on a non-existing link will throw an exception.

On the Windows platform, this will only work with directories, and the target directory must exist.


Class LinkException implements IOException

Fields
message: String
osError: OSError
path: String
Constructors
LinkException(String message, String path, OSError osError)
Methods
toString(): String

Fields

final String message
final OSError osError
final String path

Constructors

LinkException(String message, String path, OSError osError)

Methods

String toString()

Returns a string representation of this object.


Abstract class NetworkInterface

Fields
addresses: List
name: String
Getters and Setters
addresses: List<InternetAddress>
name: String
Constructors
NetworkInterface()
Methods
list(bool includeLoopback, bool includeLinkLocal, InternetAddressType type): Future<List<NetworkInterface>>

A NetworkInterface represent an active network interface on the current system. It contains a list of InternetAddresss, that's bound to the interface.

Fields

final List addresses
final String name

Getters and Setters

List<InternetAddress> get addresses

Get a list of InternetAddresss currently bound to this NetworkInterface.

String get name

Get the name of the NetworkInterface.

Constructors

NetworkInterface()

Methods

static Future<List<NetworkInterface>> list(bool includeLoopback, bool includeLinkLocal, InternetAddressType type)

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.IP_V4 or InternetAddressType.IP_V6 it will only lookup addresses of the specified type. Default is InternetAddressType.ANY.


Class OSError

Static Fields
noErrorCode: int
Fields
errorCode: int
message: String
Constructors
OSError(String message, int errorCode)
Methods
toString(): String

An OSError object holds information about an error from the operating system.

Static Fields

static const int noErrorCode = -1

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

Fields

final int errorCode

Error code supplied by the operating system. Will have the value noErrorCode if there is no error code associated with the error.

final String message

Error message supplied by the operating system. null if no message is associated with the error.

Constructors

OSError(String message, int errorCode)

Creates an OSError object from a message and an errorCode.

Methods

String toString()

Converts an OSError object to a string representation.


Abstract class Options

Fields
arguments: List
executable: String
script: String
version: String
Getters and Setters
arguments: List<String>
executable: String
script: String
version: String
Constructors
Options()

The Options object allows accessing the arguments which have been passed to the current isolate.

Fields

final List arguments
final String executable
final String script
final String version

Getters and Setters

List<String> get arguments

Returns a list of arguments that have been passed to this isolate. Any modifications to the list will be contained to the options object owning this list.

If the execution environment does not support arguments an empty list is returned.

String get executable

Returns the path of the executable used to run the script in this isolate.

If the execution environment does not support executable an empty string is returned.

String get script

Returns the path of the script being run in this isolate.

If the executable environment does not support script an empty string is returned.

String get version

Returns the version of the current Dart runtime.

Constructors

factory Options()

A newly constructed Options object contains the arguments exactly as they have been passed to the isolate.


Class Platform

Static Fields
environment: Map
executable: String
executableArguments: List
isAndroid: bool
isLinux: bool
isMacOS: bool
isWindows: bool
localHostname: String
numberOfProcessors: int
operatingSystem: String
packageRoot: String
pathSeparator: String
script: String
version: String
Getters and Setters
environment: Map<String, String>
executable: String
executableArguments: List<String>
isAndroid: bool
isLinux: bool
isMacOS: bool
isWindows: bool
localHostname: String
numberOfProcessors: int
operatingSystem: String
packageRoot: String
pathSeparator: String
script: String
version: String
Constructors
Platform()

The Platform class exposes details of the machine and operating system.

Static Fields

static final Map environment
static final String executable
static final List executableArguments
static final bool isAndroid
static final bool isLinux
static final bool isMacOS
static final bool isWindows
static final String localHostname
static final int numberOfProcessors
static final String operatingSystem
static final String packageRoot
static final String pathSeparator
static final String script
static final String version

Getters and Setters

static Map<String, String> get environment

Get the environment for this process.

Environment variables on Windows are case-insensitive. The map returned on Windows is therefore case-insensitive and will convert all keys to upper case. On other platforms the returned map is a standard case-sensitive map.

static String get executable

Returns the path of the executable used to run the script in this isolate.

If the execution environment does not support executable an empty string is returned.

static List<String> get executableArguments

Returns the flags passed to the executable used to run the script in this isolate. These are the command-line flags between the executable name and the script name. Each fetch of executableArguments returns a new List, containing the flags passed to the executable.

static bool get isAndroid

Returns true if the operating system is Android.

static bool get isLinux

Returns true if the operating system is Linux.

static bool get isMacOS

Returns true if the operating system is Mac OS.

static bool get isWindows

Returns true if the operating system is Windows.

static String get localHostname

Get the local hostname for the system.

static int get numberOfProcessors

Get the number of processors of the machine.

static String get operatingSystem

Get a string (linux, macos, windows or android) representing the operating system.

static String get packageRoot

Returns the value of the --package-root flag passed to the executable used to run the script in this isolate. This is the directory in which Dart packages are looked up.

If there is no --package-root flag, then the empty string is returned.

static String get pathSeparator

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

static String get script

Returns the URI (in String form) of the script being run in this isolate. If the URI is relative it is relative to the file URI of the working directory of the VM when it was started.

If the executable environment does not support script an empty string is returned.

static String get version

Returns the version of the current Dart runtime.

Constructors

Platform()

Abstract class Process

Fields
exitCode: Future
pid: int
stderr: Stream
stdin: IOSink
stdout: Stream
Getters and Setters
pid: int
stderr: Stream<List<int>>
stdin: IOSink
stdout: Stream<List<int>>
Constructors
Process()
Methods
kill(ProcessSignal signal): bool
run(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell, Encoding stdoutEncoding, Encoding stderrEncoding): Future<ProcessResult>
runSync(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell, Encoding stdoutEncoding, Encoding stderrEncoding): ProcessResult
start(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell): Future<Process>

Process is used to start new processes using the static start() and run() methods.

Fields

Future exitCode

Returns a Future which completes with the exit code of the process when the process completes.

Throws an UnsupportedError if the process is non-interactive.

final int pid
final Stream stderr
final IOSink stdin
final Stream stdout

Getters and Setters

int get pid

Returns the process id of the process.

Stream<List<int>> get stderr

Returns the standard error stream of the process as a Stream.

Throws an UnsupportedError if the process is non-interactive.

IOSink get stdin

Returns the standard input stream of the process as an IOSink.

Throws an UnsupportedError if the process is non-interactive.

Stream<List<int>> get stdout

Returns the standard output stream of the process as a Stream.

Throws an UnsupportedError if the process is non-interactive.

Constructors

Process()

Methods

bool kill(ProcessSignal signal)

On Windows, kill kills the process, ignoring the signal flag. On Posix systems, kill sends signal to the process. Depending on the signal giving, it'll have different meanings. When the process terminates as a result of calling kill onExit is called.

Returns true if the process is successfully killed (the signal is successfully sent). Returns false if the process could not be killed (the signal could not be sent). Usually, a false return value from kill means that the process is already dead.

static Future<ProcessResult> run(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell, Encoding stdoutEncoding, Encoding stderrEncoding)

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

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 Mac OS, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

The encoding used for decoding stdout and stderr into text is controlled through stdoutEncoding and stderrEncoding. The default encoding is SYSTEM_ENCODING. 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 in.

static ProcessResult runSync(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell, Encoding stdoutEncoding, Encoding stderrEncoding)

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 in.

static Future<Process> start(String executable, List<String> arguments, String workingDirectory, Map<String, String> environment, bool includeParentEnvironment, bool runInShell)

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.

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 Mac OS, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

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 freed since there is still pending data.


Class ProcessException implements IOException

Fields
arguments: List
errorCode: int
executable: String
message: String
Constructors
ProcessException(String executable, List<String> arguments, String message, int errorCode)
Methods
toString(): String

Fields

final List arguments

Contains the arguments provided for the process.

final int errorCode

Contains the OS error code for the process exception if any.

final String executable

Contains the executable provided for the process.

final String message

Contains the system message for the process exception if any.

Constructors

ProcessException(String executable, List<String> arguments, String message, int errorCode)

Methods

String toString()

Returns a string representation of this object.


Abstract class ProcessResult

Fields
exitCode: int
pid: int
stderr: dynamic
stdout: dynamic
Getters and Setters
exitCode: int
pid: int
stderr: dynamic
stdout: dynamic
Constructors
ProcessResult()

ProcessResult represents the result of running a non-interactive process started with Process.run.

Fields

final int exitCode
final int pid
final dynamic stderr
final dynamic stdout

Getters and Setters

int get exitCode

Exit code for the process.

int get pid

Process id from the process.

dynamic get stderr

Standard error from the process. The value used for the stderrEncoding argument to Process.run determins the type. If null was used this value is of type `List<int> otherwise it is of type String.

dynamic get stdout

Standard output from the process. The value used for the stdoutEncoding argument to Process.run determins the type. If null was used this value is of type `List<int> otherwise it is of type String.

Constructors

ProcessResult()

Class ProcessSignal

Static Fields
SIGABRT: ProcessSignal
SIGALRM: ProcessSignal
SIGBUS: ProcessSignal
SIGCHLD: ProcessSignal
SIGCONT: ProcessSignal
SIGFPE: ProcessSignal
SIGHUP: ProcessSignal
SIGILL: ProcessSignal
SIGINT: ProcessSignal
SIGKILL: ProcessSignal
SIGPIPE: ProcessSignal
SIGPOLL: ProcessSignal
SIGPROF: ProcessSignal
SIGQUIT: ProcessSignal
SIGSEGV: ProcessSignal
SIGSTOP: ProcessSignal
SIGSYS: ProcessSignal
SIGTERM: ProcessSignal
SIGTRAP: ProcessSignal
SIGTSTP: ProcessSignal
SIGTTIN: ProcessSignal
SIGTTOU: ProcessSignal
SIGURG: ProcessSignal
SIGUSR1: ProcessSignal
SIGUSR2: ProcessSignal
SIGVTALRM: ProcessSignal
SIGXCPU: ProcessSignal
SIGXFSZ: ProcessSignal

On Posix systems, ProcessSignal is used to send a specific signal to a child process, see Process.kill.

Static Fields

static const ProcessSignal SIGABRT
static const ProcessSignal SIGALRM
static const ProcessSignal SIGBUS
static const ProcessSignal SIGCHLD
static const ProcessSignal SIGCONT
static const ProcessSignal SIGFPE
static const ProcessSignal SIGHUP
static const ProcessSignal SIGILL
static const ProcessSignal SIGINT
static const ProcessSignal SIGKILL
static const ProcessSignal SIGPIPE
static const ProcessSignal SIGPOLL
static const ProcessSignal SIGPROF
static const ProcessSignal SIGQUIT
static const ProcessSignal SIGSEGV
static const ProcessSignal SIGSTOP
static const ProcessSignal SIGSYS
static const ProcessSignal SIGTERM
static const ProcessSignal SIGTRAP
static const ProcessSignal SIGTSTP
static const ProcessSignal SIGTTIN
static const ProcessSignal SIGTTOU
static const ProcessSignal SIGURG
static const ProcessSignal SIGUSR1
static const ProcessSignal SIGUSR2
static const ProcessSignal SIGVTALRM
static const ProcessSignal SIGXCPU
static const ProcessSignal SIGXFSZ

Abstract class RandomAccessFile

Fields
path: String
Getters and Setters
path: String
Constructors
RandomAccessFile()
Methods
close(): Future<RandomAccessFile>
closeSync(): void
flush(): Future<RandomAccessFile>
flushSync(): void
length(): Future<int>
lengthSync(): int
position(): Future<int>
positionSync(): int
read(int bytes): Future<List<int>>
readByte(): Future<int>
readByteSync(): int
readInto(List<int> buffer, int start, int end): Future<int>
readIntoSync(List<int> buffer, int start, int end): int
readSync(int bytes): List<int>
setPosition(int position): Future<RandomAccessFile>
setPositionSync(int position): void
toString(): String
truncate(int length): Future<RandomAccessFile>
truncateSync(int length): void
writeByte(int value): Future<RandomAccessFile>
writeByteSync(int value): int
writeFrom(List<int> buffer, int start, int end): Future<RandomAccessFile>
writeFromSync(List<int> buffer, int start, int end): void
writeString(String string, Encoding encoding): Future<RandomAccessFile>
writeStringSync(String string, Encoding encoding): void

RandomAccessFile provides random access to the data in a file. RandomAccessFile objects are obtained by calling the open method on a File object.

Fields

final String path

Getters and Setters

String get path

Gets the path of the file underlying this RandomAccessFile.

Constructors

RandomAccessFile()

Methods

Future<RandomAccessFile> close()

Closes the file. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when it has been closed.

void closeSync()

Synchronously closes the file.

Throws a FileException if the operation fails.

Future<RandomAccessFile> flush()

Flushes the contents of the file to disk. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the flush operation completes.

void flushSync()

Synchronously flushes the contents of the file to disk.

Throws a FileException if the operation fails.

Future<int> length()

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

int lengthSync()

Synchronously gets the length of the file.

Throws a FileException if the operation fails.

Future<int> position()

Gets the current byte position in the file. Returns a Future<int> that completes with the position.

int positionSync()

Synchronously gets the current byte position in the file.

Throws a FileException if the operation fails.

Future<List<int>> read(int bytes)

Reads bytes bytes from a file and returns the result as a list of bytes.

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.

int readByteSync()

Synchronously reads a single byte from the file. If end-of-file has been reached -1 is returned.

Throws a FileException if the operation fails.

Future<int> readInto(List<int> buffer, int start, int end)

Reads into an existing List<int> from the file. If start is present, the bytes will be filled into buffer from at index start, otherwise index 0. If end is present, the end - start bytes will be read into buffer, otherwise up to buffer.length. If end == start nothing happends.

Returns a Future<int> that completes with the number of bytes read.

int readIntoSync(List<int> buffer, int start, int end)

Synchronously reads into an existing List<int> from the file. If start is present, the bytes will be filled into buffer from at index start, otherwise index 0. If end is present, the end - start bytes will be read into buffer, otherwise up to buffer.length. If end == start nothing happends.

Throws a FileException if the operation fails.

List<int> readSync(int bytes)

Synchronously reads a maximum of bytes bytes from a file and returns the result in a list of bytes.

Throws a FileException if the operation fails.

Future<RandomAccessFile> setPosition(int position)

Sets the byte position in the file. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the position has been set.

void setPositionSync(int position)

Synchronously sets the byte position in the file.

Throws a FileException if the operation fails.

String toString()

Returns a human-readable string for this RandomAccessFile instance.

Future<RandomAccessFile> truncate(int length)

Truncates (or extends) the file to length bytes. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the truncation has been performed.

void truncateSync(int length)

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

Throws a FileException if the operation fails.

Future<RandomAccessFile> writeByte(int value)

Writes a single byte to the file. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the write completes.

int writeByteSync(int value)

Synchronously writes a single byte to the file. Returns the number of bytes successfully written.

Throws a FileException if the operation fails.

Future<RandomAccessFile> writeFrom(List<int> buffer, int start, int end)

Writes from a List<int> to the file. It will read the buffer from index start to index end. If start is omitted, it'll start from index 0. If end is omitted, it will write to end of buffer.

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

void writeFromSync(List<int> buffer, int start, int end)

Synchronously writes from a List<int> to the file. It will read the buffer from index start to index end. If start is omitted, it'll start from index 0. If end is omitted, it will write to the end of buffer.

Throws a FileException if the operation fails.

Future<RandomAccessFile> writeString(String string, Encoding encoding)

Writes a string to the file using the given Encoding. Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the write completes.

void writeStringSync(String string, Encoding encoding)

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

Throws a FileException if the operation fails.


Class RawSecureServerSocket extends Stream<RawSecureSocket>

Fields
certificateName: String
port: int
requestClientCertificate: bool
requireClientCertificate: bool
Getters and Setters
port: int
Methods
bind(String address, int port, String certificateName, int backlog, bool v6Only, bool requestClientCertificate, bool requireClientCertificate): Future<RawSecureServerSocket>
close(): Future<RawSecureServerSocket>
listen( onData, onError, onDone, bool cancelOnError): StreamSubscription<RawSecureSocket>

The RawSecureServerSocket is a server socket, providing a stream of low-level RawSecureSockets.

See RawSecureSocket for more info.

Fields

final String certificateName
final int port
final bool requestClientCertificate
final bool requireClientCertificate

Getters and Setters

int get port

Returns the port used by this socket.

Methods

static Future<RawSecureServerSocket> bind(String address, int port, String certificateName, int backlog, bool v6Only, bool requestClientCertificate, bool requireClientCertificate)

Returns a future for a RawSecureServerSocket. When the 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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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 given by certificateName.

address must be given as a numeric address, not a host name.

certificateName is the nickname or the distinguished name (DN) of the certificate in the certificate database. It is looked up in the NSS certificate database set by SecureSocket.setCertificateDatabase. If certificateName contains "CN=", it is assumed to be a distinguished name. Otherwise, it is looked up as a nickname.

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.

Future<RawSecureServerSocket> close()

Closes the socket. The returned future completes when the socket is fully closed and is no longer bound.

StreamSubscription<RawSecureSocket> listen( onData, onError, onDone, bool cancelOnError)

Adds a subscription to this stream.

On each data event from this stream, the subscriber's onData handler is called. If onData is null, nothing happens.

On errors from this stream, the onError handler is given a object describing the error.

If this stream closes, the onDone handler is called.

If cancelOnError is true, the subscription is ended when the first error is reported. The default is false.


Abstract class RawSecureSocket implements RawSocket

Fields
peerCertificate: X509Certificate
Getters and Setters
peerCertificate: X509Certificate
Constructors
RawSecureSocket()
Methods
connect(dynamic host, int port, bool sendClientCertificate, String certificateName, onBadCertificate): Future<RawSecureSocket>
renegotiate(bool useSessionCache, bool requestClientCertificate, bool requireClientCertificate): void
secure(RawSocket socket, StreamSubscription<dynamic> subscription, dynamic host, bool sendClientCertificate, String certificateName, onBadCertificate): Future<RawSecureSocket>
secureServer(RawSocket socket, String certificateName, StreamSubscription<dynamic> subscription, List<int> bufferedData, bool requestClientCertificate, bool requireClientCertificate): Future<RawSecureSocket>

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 certificate database provided in SecureSocket.initialize, and/or the default built-in root certificates.

Fields

final X509Certificate peerCertificate

Getters and Setters

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.

Constructors

RawSecureSocket()

Methods

static Future<RawSecureSocket> connect(dynamic host, int port, bool sendClientCertificate, String certificateName, onBadCertificate)

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 certificate database provided in SecureSocket.initialize, and/or the default built-in root certificates. If sendClientCertificate is set to true, the socket will send a client certificate if one is requested by the server. If certificateName is the nickname of a certificate in the certificate database, that certificate will be sent. If certificateName is null, which is the usual use case, an appropriate certificate will be searched for in the database and sent automatically, based on what the server says it will accept.

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.

void renegotiate(bool useSessionCache, bool requestClientCertificate, bool requireClientCertificate)

Renegotiate an existing secure connection, renewing the session keys and possibly changing the connection properties.

This repeats the SSL or TLS handshake, with options that allow clearing the session cache and requesting a client certificate.

static Future<RawSecureSocket> secure(RawSocket socket, StreamSubscription<dynamic> subscription, dynamic host, bool sendClientCertificate, String certificateName, onBadCertificate)

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 socket will take over the subscription and process any subsequent events. In most cases calling pause on this subscription before starting TLS handshake is the right thing to do.

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.

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.

static Future<RawSecureSocket> secureServer(RawSocket socket, String certificateName, StreamSubscription<dynamic> subscription, List<int> bufferedData, bool requestClientCertificate, bool requireClientCertificate)

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 secure socket will take over the subscription and process any subsequent events.

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.


Abstract class RawServerSocket implements Stream<RawSocket>

Fields
port: int
Getters and Setters
port: int
Constructors
RawServerSocket()
Methods
bind(dynamic address, int port, int backlog, bool v6Only): Future<RawServerSocket>
close(): Future<RawServerSocket>

A RawServerSocket represents a listening socket, and provides a stream of low-level RawSocket objects, one for each connection made to the listening socket.

See RawSocket for more info.

Fields

final int port

Getters and Setters

int get port

Returns the port used by this socket.

Constructors

RawServerSocket()

Methods

static Future<RawServerSocket> bind(dynamic address, int port, int backlog, bool v6Only)

Returns a future for a RawServerSocket. When the 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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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.

Future<RawServerSocket> close()

Closes the socket. The returned future completes when the socket is fully closed and is no longer bound.


Abstract class RawSocket implements Stream<RawSocketEvent>

Fields
address: InternetAddress
port: int
readEventsEnabled: bool
remoteHost: String
remotePort: int
writeEventsEnabled: bool
Getters and Setters
address: InternetAddress
port: int
remoteHost: String
remotePort: int
Constructors
RawSocket()
Methods
available(): int
close(): Future<RawSocket>
connect(dynamic host, int port): Future<RawSocket>
read(int len): List<int>
setOption(SocketOption option, bool enabled): bool
shutdown(SocketDirection direction): void
write(List<int> buffer, int offset, int count): int

The RawSocket is a low-level interface to a socket, exposing the raw events signaled by the system. It's a Stream of RawSocketEvents.

Fields

final InternetAddress address
final int port
bool readEventsEnabled

Set or get, if the RawSocket should listen for RawSocketEvent.READ events. Default is true.

final String remoteHost
final int remotePort
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.

Getters and Setters

InternetAddress get address

Returns the InternetAddress used to connect this socket.

int get port

Returns the port used by this socket.

String get remoteHost

Returns the remote host connected to by this socket.

int get remotePort

Returns the remote port connected to by this socket.

Constructors

RawSocket()

Methods

int available()

Returns the number of received and non-read bytes in the socket that can be read.

Future<RawSocket> close()

Closes the socket. Returns a Future that completes with this 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.READ_CLOSED event.

static Future<RawSocket> connect(dynamic host, int port)

Creates a new socket connection to the host and port and returns a Future that will complete with either a RawSocket 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 use the first value in the list.

List<int> 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 then len if fewer bytes are available for immediate reading. If no data is available null is returned.

bool setOption(SocketOption option, bool enabled)

Use setOption to customize the RawSocket. See SocketOption for available options.

Returns true if the option was set successfully, false otherwise.

void shutdown(SocketDirection direction)

Shutdown 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.READ_CLOSED event.

int write(List<int> buffer, int offset, 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.

The default value for offset is 0, and the default value for count is buffer.length - offset.


Class RawSocketEvent

Static Fields
CLOSED: RawSocketEvent
READ: RawSocketEvent
READ_CLOSED: RawSocketEvent
WRITE: RawSocketEvent
Methods
toString(): String

Events for the RawSocket.

Static Fields

static const RawSocketEvent CLOSED
static const RawSocketEvent READ
static const RawSocketEvent READ_CLOSED
static const RawSocketEvent WRITE

Methods

String toString()

Returns a string representation of this object.


Class RedirectException implements HttpException

Fields
message: String
redirects: List
uri: Uri
Getters and Setters
uri: Uri
Constructors
RedirectException(String message, List<RedirectInfo> redirects)
Methods
toString(): String

Fields

final String message
final List redirects
final Uri uri

Getters and Setters

Uri get uri

Constructors

RedirectException(String message, List<RedirectInfo> redirects)

Methods

String toString()

Returns a string representation of this object.


Abstract class RedirectInfo

Fields
location: Uri
method: String
statusCode: int
Getters and Setters
location: Uri
method: String
statusCode: int
Constructors
RedirectInfo()

Redirect information.

Fields

final Uri location
final String method
final int statusCode

Getters and Setters

Uri get location

Returns the location for the redirect.

String get method

Returns the method used for the redirect.

int get statusCode

Returns the status code used for the redirect.

Constructors

RedirectInfo()

Class SecureServerSocket extends Stream<SecureSocket> implements ServerSocket

Fields
port: int
Getters and Setters
port: int
Methods
bind(dynamic address, int port, String certificateName, int backlog, bool v6Only, bool requestClientCertificate, bool requireClientCertificate): Future<SecureServerSocket>
close(): Future<SecureServerSocket>
listen( onData, onError, onDone, bool cancelOnError): StreamSubscription<SecureSocket>

The SecureServerSocket is a server socket, providing a stream of high-level Sockets.

See SecureSocket for more info.

Fields

final int port

Getters and Setters

int get port

Returns the port used by this socket.

Methods

static Future<SecureServerSocket> bind(dynamic address, int port, String certificateName, int backlog, bool v6Only, bool requestClientCertificate, bool requireClientCertificate)

Returns a future for a SecureServerSocket. When the 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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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 given by certificateName.

address must be given as a numeric address, not a host name.

certificateName is the nickname or the distinguished name (DN) of the certificate in the certificate database. It is looked up in the NSS certificate database set by SecureSocket.setCertificateDatabase. If certificateName contains "CN=", it is assumed to be a distinguished name. Otherwise, it is looked up as a nickname.

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 one doesn't need to set both to true. To check whether a client certificate was received, check SecureSocket.peerCertificate after connecting. If no certificate was received, the result will be null.

Future<SecureServerSocket> close()

Closes the socket. The returned future completes when the socket is fully closed and is no longer bound.

StreamSubscription<SecureSocket> listen( onData, onError, onDone, bool cancelOnError)

Adds a subscription to this stream.

On each data event from this stream, the subscriber's onData handler is called. If onData is null, nothing happens.

On errors from this stream, the onError handler is given a object describing the error.

If this stream closes, the onDone handler is called.

If cancelOnError is true, the subscription is ended when the first error is reported. The default is false.


Abstract class SecureSocket implements Socket

Fields
peerCertificate: X509Certificate
Getters and Setters
peerCertificate: X509Certificate
Methods
connect(dynamic host, int port, bool sendClientCertificate, String certificateName, onBadCertificate): Future<SecureSocket>
initialize(String database, String password, bool useBuiltinRoots): void
renegotiate(bool useSessionCache, bool requestClientCertificate, bool requireClientCertificate): void
secure(Socket socket, dynamic host, bool sendClientCertificate, String certificateName, onBadCertificate): Future<SecureSocket>
secureServer(Socket socket, String certificateName, List<int> bufferedData, bool requestClientCertificate, bool requireClientCertificate): Future<SecureSocket>

A high-level class for communicating securely over a TCP socket, using TLS and SSL. The SecureSocket exposes both a Stream and an IOSink interface, making it ideal for using together with other Streams.

Fields

final X509Certificate peerCertificate

Getters and Setters

X509Certificate get peerCertificate

Get 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 it is the client end, peerCertificate will return the server's certificate.

Methods

static Future<SecureSocket> connect(dynamic host, int port, bool sendClientCertificate, String certificateName, onBadCertificate)

Constructs a new secure client socket and connect it to the given host on port port. The returned Future will complete with a SecureSocket that is connected and ready for subscription.

If sendClientCertificate is set to true, the socket will send a client certificate if one is requested by the server.

If certificateName is the nickname of a certificate in the certificate database, that certificate will be sent.

If certificateName is null, which is the usual use case, an appropriate certificate will be searched for in the database and sent automatically, based on what the server says it will accept.

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.

static void initialize(String database, String password, bool useBuiltinRoots)

Initializes the NSS library. If initialize is not called, the library is automatically initialized as if initialize were called with no arguments. If initialize is called more than once, or called after automatic initialization has happened (when a secure connection is made), then a TlsException is thrown.

The optional argument database is the path to a certificate database directory containing root certificates for verifying certificate paths on client connections, and server certificates to provide on server connections. The argument password should be used when creating secure server sockets, to allow the private key of the server certificate to be fetched. If useBuiltinRoots is true (the default), then a built-in set of root certificates for trusted certificate authorities is merged with the certificates in the database. The list of built-in root certificates, and documentation about this default database, is available at http://www.mozilla.org/projects/security/certs/included/ .

If the database argument is omitted, then only the builtin root certificates are used. If useBuiltinRoots is also false, then no certificates are available.

Examples: 1) Use only the builtin root certificates:

SecureSocket.initialize(); or
2) Use a specified database directory and the builtin roots:
SecureSocket.initialize(database: 'path/to/my/database',
                        password: 'my_password');
3) Use a specified database directory, without builtin roots:
SecureSocket.initialize(database: 'path/to/my/database',
                        password: 'my_password'.
                        useBuiltinRoots: false);
The database should be an NSS certificate database directory containing a cert9.db file, not a cert8.db file. This version of the database can be created using the NSS certutil tool with "sql:" in front of the absolute path of the database directory, or setting the environment variable [NSS_DEFAULT_DB_TYPE] to "sql".

void renegotiate(bool useSessionCache, bool requestClientCertificate, bool requireClientCertificate)

Renegotiate an existing secure connection, renewing the session keys and possibly changing the connection properties.

This repeats the SSL or TLS handshake, with options that allow clearing the session cache and requesting a client certificate.

static Future<SecureSocket> secure(Socket socket, dynamic host, bool sendClientCertificate, String certificateName, onBadCertificate)

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 pause on this subscription before starting TLS handshake is the right thing to do.

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.

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.

static Future<SecureSocket> secureServer(Socket socket, String certificateName, List<int> bufferedData, bool requestClientCertificate, bool requireClientCertificate)

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 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.


Abstract class ServerSocket implements Stream<Socket>

Fields
port: int
Getters and Setters
port: int
Constructors
ServerSocket()
Methods
bind(dynamic address, int port, int backlog, bool v6Only): Future<ServerSocket>
close(): Future<ServerSocket>

A ServerSocket represents a listening socket, and provides a stream of Socket objects, one for each connection made to the listening socket.

See Socket for more info.

Fields

final int port

Getters and Setters

int get port

Returns the port used by this socket.

Constructors

ServerSocket()

Methods

static Future<ServerSocket> bind(dynamic address, int port, int backlog, bool v6Only)

Returns a future for a ServerSocket. When the 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.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 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.

Future<ServerSocket> close()

Closes the socket. The returned future completes when the socket is fully closed and is no longer bound.


Abstract class Socket implements Stream<List<int>>, IOSink

Fields
address: InternetAddress
port: int
remoteHost: String
remotePort: int
Getters and Setters
address: InternetAddress
port: int
remoteHost: String
remotePort: int
Constructors
Socket()
Methods
connect(dynamic host, int port): Future<Socket>
destroy(): void
setOption(SocketOption option, bool enabled): bool

A high-level class for communicating over a TCP socket.

The Socket exposes both a Stream and a IOSink interface, making it ideal for using together with other Streams.

Fields

final InternetAddress address
final int port
final String remoteHost
final int remotePort

Getters and Setters

InternetAddress get address

Returns the InternetAddress used to connect this socket.

int get port

Returns the port used by this socket.

String get remoteHost

Returns the remote host connected to by this socket.

int get remotePort

Returns the remote port connected to by this socket.

Constructors

Socket()

Methods

static Future<Socket> connect(dynamic host, int port)

Creats 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 use the first value in the list.

void destroy()

Destroy 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.

bool setOption(SocketOption option, bool enabled)

Use setOption to customize the RawSocket. See SocketOption for available options.

Returns true if the option was set successfully, false otherwise.


Class SocketDirection

Static Fields
BOTH: SocketDirection
RECEIVE: SocketDirection
SEND: SocketDirection

The SocketDirection is used as a parameter to Socket.close and RawSocket.close to close a socket in the specified direction(s).

Static Fields

static const SocketDirection BOTH
static const SocketDirection RECEIVE
static const SocketDirection SEND

Class SocketException implements IOException

Fields
address: InternetAddress
message: String
osError: OSError
port: int
Constructors
SocketException(String message, OSError osError, InternetAddress address, int port)
Methods
toString(): String

Fields

final InternetAddress address
final String message
final OSError osError
final int port

Constructors

SocketException(String message, OSError osError, InternetAddress address, int port)

Methods

String toString()

Returns a string representation of this object.


Class SocketOption

Static Fields
TCP_NODELAY: SocketOption

The SocketOption is used as a parameter to Socket.setOption and RawSocket.setOption to set customize the behaviour of the underlying socket.

Static Fields

static const SocketOption TCP_NODELAY

Enable or disable no-delay on the socket. If TCP_NODELAY is enabled, the socket will not buffer data internally, but instead write each data chunk as an invidual TCP packet.

TCP_NODELAY is disabled by default.


Class Stdin extends _StdStream implements Stream<List<int>>

Fields
echoMode: bool
lineMode: bool
Getters and Setters
echoMode=(bool enabled)
lineMode=(bool enabled)
Methods
readByteSync(): int
readLineSync(Encoding encoding, bool retainNewlines): String

Stdin allows both synchronous and asynchronous reads from the standard input stream.

Mixing synchronous and asynchronous reads is undefined.

Fields

bool echoMode
bool lineMode

Getters and Setters

set echoMode=(bool enabled)

Enable or disable echo mode on the Stdin.

If disabled, input from to console will not be echoed.

Default depends on the parent process, but usually enabled.

set lineMode=(bool enabled)

Enable or disable line mode on the Stdin.

If enabled, characters are delayed until a new-line character is entered. If disabled, characters will be available as typed.

Default depends on the parent process, but usually enabled.

Methods

int readByteSync()

Synchronously read a byte from stdin. This call will block until a byte is available.

If at end of file, -1 is returned.

String readLineSync(Encoding encoding, bool retainNewlines)

Synchronously read a line from stdin. This call will block until a full line is available. The line will contain the newline character(s).

If end-of-file is reached, null is returned.

If end-of-file is reached after some data has already been read, that data is returned.


Class StdioType

Static Fields
FILE: StdioType
OTHER: StdioType
PIPE: StdioType
TERMINAL: StdioType
Fields
name: String
Methods
toString(): String

Static Fields

static const StdioType FILE
static const StdioType OTHER
static const StdioType PIPE
static const StdioType TERMINAL

Fields

final String name

Methods

String toString()

Returns a string representation of this object.


Class SystemEncoding extends Encoding

Fields
decoder: Converter
encoder: Converter
Getters and Setters
decoder: Converter<List<int>, String>
encoder: Converter<String, List<int>>
Constructors
SystemEncoding()
Methods
decode(List<int> encoded): String
encode(String input): List<int>

The system encoding is the current code page on Windows and UTF-8 on Linux and Mac.

Fields

final Converter decoder
final Converter encoder

Getters and Setters

Converter<List<int>, String> get decoder
Converter<String, List<int>> get encoder

Constructors

SystemEncoding()

Methods

String decode(List<int> encoded)
List<int> encode(String input)

Class TlsException implements IOException

Fields
message: String
osError: OSError
type: String
Constructors
TlsException(String message, OSError osError)
Methods
toString(): String

A secure networking exception caused by a failure in the TLS/SSL protocol.

Fields

final String message
final OSError osError
final String type

Constructors

TlsException(String message, OSError osError)

Methods

String toString()

Returns a string representation of this object.


Abstract class WebSocket implements Stream<dynamic>, StreamSink<dynamic>

Static Fields
CLOSED: int
CLOSING: int
CONNECTING: int
OPEN: int
Fields
closeCode: int
closeReason: String
extensions: String
pingInterval: Duration
protocol: String
readyState: int
Getters and Setters
closeCode: int
closeReason: String
extensions: String
protocol: String
readyState: int
Constructors
WebSocket()
Methods
add(dynamic data): void
addStream(Stream<dynamic> stream): Future<dynamic>
close(int code, String reason): Future<dynamic>
connect(String url, dynamic protocols): Future<WebSocket>

A two-way HTTP communication object for client or server applications.

The stream exposes the messages received. A text message will be of type String and a binary message will be of type List<int>.

Static Fields

static const int CLOSED = 3
static const int CLOSING = 2
static const int CONNECTING = 0

Possible states of the connection.

static const int OPEN = 1

Fields

final int closeCode
final String closeReason
final String extensions
Duration pingInterval

Set and get the interval for sending ping signals. If a ping message is not answered by a pong message from the peer, the WebSocket is assumed disconnected and the connection is closed with a WebSocketStatus.GOING_AWAY close code. When a ping signal is sent, the pong message must be received within pingInterval.

There are never two outstanding pings at any given time, and the next ping timer starts when the pong is received.

Set the pingInterval to null to disable sending ping messages.

The default value is null.

final String protocol
final int readyState

Getters and Setters

int get closeCode

The close code set when the web socket connection is closed. If there is no close code available this property will be null

String get closeReason

The close reason set when the web socket connection is closed. If there is no close reason available this property will be null

String get extensions

The extensions property is initially the empty string. After the web socket connection is established this string reflects the extensions used by the server.

String get protocol

The protocol property is initially the empty string. After the web socket connection is established the value is the subprotocol selected by the server. If no subprotocol is negotiated the value will remain null.

int get readyState

Returns the current state of the connection.

Constructors

WebSocket()

Methods

void add(dynamic data)

Sends data on the web socket connection. The data in data must be either a String, or a List<int> holding bytes.

Future<dynamic> addStream(Stream<dynamic> stream)

Sends data from a stream on web socket connection. Each data event from stream will be send as a single WebSocket frame. The data from stream must be either Strings, or List<int>s holding bytes.

Future<dynamic> close(int code, String reason)

Closes the web socket connection. Set the optional code and reason arguments to send close information to the remote peer. If they are omitted, the peer will see WebSocketStatus.NO_STATUS_RECEIVED code with no reason.

static Future<WebSocket> connect(String url, dynamic protocols)

Create a new web socket connection. The URL supplied in url must use the scheme ws or wss. The protocols argument is either a String or List<String> specifying the subprotocols the client is willing to speak.


Class WebSocketException implements IOException

Fields
message: String
Constructors
WebSocketException(String message)
Methods
toString(): String

Fields

final String message

Constructors

WebSocketException(String message)

Methods

String toString()

Returns a string representation of this object.


Abstract class WebSocketStatus

Static Fields
ABNORMAL_CLOSURE: int
GOING_AWAY: int
INTERNAL_SERVER_ERROR: int
INVALID_FRAME_PAYLOAD_DATA: int
MESSAGE_TOO_BIG: int
MISSING_MANDATORY_EXTENSION: int
NORMAL_CLOSURE: int
NO_STATUS_RECEIVED: int
POLICY_VIOLATION: int
PROTOCOL_ERROR: int
RESERVED_1004: int
RESERVED_1015: int
UNSUPPORTED_DATA: int
Constructors
WebSocketStatus()

Web socket status codes used when closing a web socket connection.

Static Fields

static const int ABNORMAL_CLOSURE = 1006
static const int GOING_AWAY = 1001
static const int INTERNAL_SERVER_ERROR = 1011
static const int INVALID_FRAME_PAYLOAD_DATA = 1007
static const int MESSAGE_TOO_BIG = 1009
static const int MISSING_MANDATORY_EXTENSION = 1010
static const int NORMAL_CLOSURE = 1000
static const int NO_STATUS_RECEIVED = 1005
static const int POLICY_VIOLATION = 1008
static const int PROTOCOL_ERROR = 1002
static const int RESERVED_1004 = 1004
static const int RESERVED_1015 = 1015
static const int UNSUPPORTED_DATA = 1003

Constructors

WebSocketStatus()

Abstract class WebSocketTransformer implements StreamTransformer<HttpRequest, WebSocket>

Constructors
WebSocketTransformer()
Methods
isUpgradeRequest(HttpRequest request): bool
upgrade(HttpRequest request): Future<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 web sockets as specified by RFC6455.

Constructors

factory WebSocketTransformer()

Methods

static bool isUpgradeRequest(HttpRequest request)

Checks whether the request is a valid WebSocket upgrade request.

static Future<WebSocket> upgrade(HttpRequest request)

Upgrades a HttpRequest to a WebSocket connection. If the request is not a valid web socket upgrade request a HTTP response with status code 500 will be returned. Otherwise the returned future will complete with the WebSocket when the upgrade pocess is complete.


Class X509Certificate

Fields
endValidity: DateTime
issuer: String
startValidity: DateTime
subject: String
Constructors
X509Certificate(String subject, String issuer, DateTime startValidity, DateTime endValidity)

X509Certificate represents an SSL certificate, with accessors to get the fields of the certificate.

Fields

final DateTime endValidity
final String issuer
final DateTime startValidity
final String subject

Constructors

X509Certificate(String subject, String issuer, DateTime startValidity, DateTime endValidity)

Class ZLibCodec extends Codec<List<int>, List<int>>

Fields
decoder: Converter
encoder: Converter
level: int
Getters and Setters
decoder: Converter<List<int>, List<int>>
encoder: Converter<List<int>, List<int>>
Constructors
ZLibCodec(int level)

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

Fields

final Converter decoder
final Converter encoder
final int level

The compression level of the ZLibCodec.

Getters and Setters

Converter<List<int>, List<int>> get decoder

Get a Converter for decoding ZLib compressed data.

Converter<List<int>, List<int>> get encoder

Get a Converter for encoding to ZLib compressed data.

Constructors

ZLibCodec(int level)

The compression-level can be set in the range of 1..10, 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, but at the cost of lower compression rates.


Class ZLibDecoder extends Converter<List<int>, List<int>>

Constructors
ZLibDecoder()
Methods
convert(List<int> bytes): List<int>
startChunkedConversion(ChunkedConversionSink<List<int>> sink): ByteConversionSink

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

Constructors

ZLibDecoder()

Create a new ZLibEncoder converter.

Methods

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

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

ByteConversionSink startChunkedConversion(ChunkedConversionSink<List<int>> sink)

Start a chunked conversion. While it accepts any ChunkedConversionSink taking List<int>'s, the optimal sink to be passed as sink is a ByteConversionSink.


Class ZLibEncoder extends Converter<List<int>, List<int>>

Fields
gzip: bool
level: int
Constructors
ZLibEncoder(bool gzip, int level)
Methods
convert(List<int> bytes): List<int>
startChunkedConversion(ChunkedConversionSink<List<int>> sink): ByteConversionSink

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

Fields

final bool gzip

If gzip is true, GZip frames will be added to the compressed data.

final int level

The compression level used by the encoder.

Constructors

ZLibEncoder(bool gzip, int level)

Create a new ZLibEncoder converter. If the gzip flag is set, the encoder will wrap the encoded ZLib data in GZip frames.

Methods

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

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

ByteConversionSink startChunkedConversion(ChunkedConversionSink<List<int>> sink)

Start a chunked conversion using the options given to the ZLibEncoder constructor. While it accepts any ChunkedConversionSink taking List<int>'s, the optimal sink to be passed as sink is a ByteConversionSink.