RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Core libraries

Files, processes, sockets and HTTP

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

import 'raya:io';
106 classes598 functions and methods808 of 1,149 documented400 runnable examples
abstract class WebSocket implements Stream<dynamic >, StreamSink<dynamic >

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

Constructors

WebSocketconstructordeprecated
WebSocket()
factory WebSocket.fromUpgradedSocket(Socket socket, {String? protocol, bool? serverSide, CompressionOptions compression = CompressionOptions.compressionDefault, int maxPayloadLength = _kDefaultWebSocketMaxPayloadLength})

Creates a WebSocket from an already-upgraded socket.

The initial WebSocket handshake must have occurred prior to this call. A WebSocket client can automatically perform the handshake using WebSocket.connect, while a server can do so using WebSocketTransformer.upgrade. To manually upgrade an HttpRequest, HttpResponse.detachSocket may be called.

protocol should be the protocol negotiated by this handshake, if any.

serverSide must be passed explicitly. If it's false, the WebSocket will act as the client and mask the messages it sends. If it's true, it will act as the server and will not mask its messages.

If compression is provided, the WebSocket created will be configured to negotiate with the specified CompressionOptions. If none is specified then the WebSocket will be created with the default CompressionOptions. See WebSocketTransformer for maxPayloadLength.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async => (await WebSocketTransformer.upgrade(req))
    ..add('hello over a hand-made upgrade')
    ..close());
  final client = HttpClient();
  final req = await client.get('127.0.0.1', server.port, '/')
    ..headers.set('Connection', 'Upgrade')
    ..headers.set('Upgrade', 'websocket')
    ..headers.set('Sec-WebSocket-Version', '13')
    ..headers.set('Sec-WebSocket-Key', 'dGhlIHNhbXBsZSBub25jZQ==');
  final res = await req.close().timeout(t);
  final ws = WebSocket.fromUpgradedSocket(await res.detachSocket(), serverSide: false);
  print('${res.statusCode}: ${await ws.single.timeout(t)}');
  client.close(force: true);
  await server.close(force: true);
}
Output from the Raya VM
101: hello over a hand-made upgrade

Static

connectingconstant
static const int connecting = 0

Possible states of the connection.

openconstant
static const int open = 1
closingconstant
static const int closing = 2
closedconstant
static const int closed = 3
connectstaticmethod
static Future<WebSocket> connect(String url, {Iterable<String>? protocols, Map<String, dynamic>? headers, CompressionOptions compression = CompressionOptions.compressionDefault, HttpClient? customClient, int maxPayloadLength = _kDefaultWebSocketMaxPayloadLength})

Create a new WebSocket connection. The URL supplied in url must use the scheme ws or wss.

The protocols argument is specifying the subprotocols the client is willing to speak.

The headers argument is specifying additional HTTP headers for setting up the connection. This would typically be the Origin header and potentially cookies. The keys of the map are the header fields and the values are either String or List<String>.

If headers is provided, there are a number of headers which are controlled by the WebSocket connection process. These headers are:

  • connection
  • sec-websocket-key
  • sec-websocket-protocol
  • sec-websocket-version
  • upgrade

If any of these are passed in the headers map they will be ignored.

If the url contains user information this will be passed as basic authentication when setting up the connection. See WebSocketTransformer for maxPayloadLength.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.transform(WebSocketTransformer(protocolSelector: (protocols) => protocols.last)).listen((ws) {
    ws.add('protocol chosen: ${ws.protocol}');
    ws.close();
  });
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}', protocols: ['chat.v1', 'chat.v2']).timeout(t);
  print(await ws.single.timeout(t));
  print('client sees protocol ${ws.protocol}');
  await server.close(force: true);
}
Output from the Raya VM
protocol chosen: chat.v2
client sees protocol chat.v2
userAgentstaticgetter
static String? get userAgent

Gets the user agent used for WebSocket connections.

userAgentstaticsetter
static set userAgent(String? userAgent)

Sets the user agent to use for WebSocket connections.

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((req) async {
    final agent = req.headers.value('user-agent');
    final ws = await WebSocketTransformer.upgrade(req);
    ws.add('user agent: $agent');
    await ws.close();
  });
  WebSocket.userAgent = 'raya-ws-example/1.0';
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(t);
  print(await ws.single.timeout(t));
  await server.close(force: true);
}
Output from the Raya VM
user agent: raya-ws-example/1.0

Properties

Duration? pingInterval

The interval between ping signals.

A ping message is sent every pingInterval, starting at the first pingInterval after a new value has been assigned or a pong message has been received. 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.goingAway 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.

int get readyState

Returns the current state of the connection.

String get extensions

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

protocolgetter
String? get protocol

The protocol property is initially the empty string. After the WebSocket connection is established the value is the subprotocol selected by the server. If no subprotocol is negotiated the value will remain [:null:].

closeCodegetter
int? get closeCode

The close code set when the WebSocket connection is closed. If there is no close code available this property will be [:null:]

String? get closeReason

The close reason set when the WebSocket connection is closed. If there is no close reason available this property will be [:null:]

Methods

closemethod
Future close([int? code, String? reason])

Closes the WebSocket 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.noStatusReceived code with no reason.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.transform(WebSocketTransformer()).listen((ws) {
    ws.listen(null, onDone: () => print('server saw close code ${ws.closeCode}, reason "${ws.closeReason}"'));
  });
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(const Duration(seconds: 2));
  await ws.close(WebSocketStatus.normalClosure, 'bye');
  print('client closed, readyState ${ws.readyState == WebSocket.closed ? 'closed' : ws.readyState}');
  await Future.delayed(const Duration(milliseconds: 50));
  await server.close(force: true);
}
Output from the Raya VM
client closed, readyState 1
server saw close code 1000, reason "bye"
addmethod
void add(data)

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

Example
import 'raya:io';

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.transform(WebSocketTransformer()).listen((ws) {
    var n = 0;
    ws.listen((m) {
      ws.add(m is String ? 'text: $m' : 'binary: $m');
      if (++n == 2) ws.close();
    });
  });
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(t);
  ws.add('hi'); // a String is sent as a text frame
  ws.add([1, 2, 3]); // a List<int> as a binary frame
  print(await ws.toList().timeout(t));
  await server.close(force: true);
}
Output from the Raya VM
[text: hi, binary: [1, 2, 3]]
addErrormethod
void addError(Object error, [StackTrace? stackTrace])

Reports an error on this WebSocket.

This does not send an error event to the remote peer. WebSocket connections only transmit text and binary data frames.

If unhandled, the error may be reported as an uncaught asynchronous error.

addStreammethod
Future addStream(Stream stream)

Sends data from a stream on WebSocket 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.

Example
import 'raya:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  final got = <Object?>[];
  server.transform(WebSocketTransformer()).listen((ws) => ws.listen(got.add, onDone: () => print('server received: $got')));
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(const Duration(seconds: 2));
  await ws.addStream(Stream.fromIterable(['one', 'two', 'three']));
  await ws.close();
  await Future.delayed(const Duration(milliseconds: 50));
  await server.close(force: true);
}
Output from the Raya VM
server received: [one, two, three]
void addUtf8Text(List<int> bytes)

Sends a text message with the text represented by bytes.

The bytes should be valid UTF-8 encoded Unicode characters. If they are not, the receiving end will close the connection.

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

Future<void> main() async {
  const t = Duration(seconds: 2);
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.transform(WebSocketTransformer()).listen((ws) => ws.listen((m) => ws..add('${m.runtimeType}: $m')..close()));
  final ws = await WebSocket.connect('ws://127.0.0.1:${server.port}').timeout(t);
  ws.addUtf8Text(utf8.encode('déjà vu')); // already-encoded text, sent as a text frame
  print(await ws.single.timeout(t));
  await server.close(force: true);
}
Output from the Raya VM
String: déjà vu
class WebSocketException implements IOException

Constructors

const WebSocketException([this.message = "", this.httpStatusCode])
Example
import 'raya:io';

void main() {
  const e = WebSocketException('Connection was not upgraded to websocket', 404);
  print('message: ${e.message}, http status: ${e.httpStatusCode}');
}
Output
message: Connection was not upgraded to websocket, http status: 404

Properties

messagefield
final String message
final int? httpStatusCode

Methods

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

void main() {
  print(const WebSocketException('Protocol error'));
}
Output
WebSocketException: Protocol error
abstract interface class BytesBuilder

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.

Constructors

factory BytesBuilder({bool copy = true})

Construct a new empty BytesBuilder.

If copy is true (the default), the created builder is a copying builder. A copying builder maintains its own internal buffer and copies the bytes added to it eagerly.

If copy set to false, the created builder assumes that lists added to it will not change. Any Uint8List added using add is kept until toBytes or takeBytes is called, and only then are their contents copied. A non-Uint8List may be copied eagerly. If only a single Uint8List is added to the builder, that list is returned by toBytes or takeBytes directly, without any copying. A list added to a non-copying builder should not change its content after being added, and it must not change its length after being added. (Normal Uint8Lists are fixed length lists, but growing lists implementing Uint8List exist.)

Example
import 'raya:io';

void main() {
  final b = BytesBuilder(copy: false); // keeps the added lists instead of copying
  b.add([1, 2]);
  b.addByte(3);
  print('length ${b.length}, bytes ${b.toBytes()}');
}
Output
length 3, bytes [1, 2, 3]

Properties

lengthgetter
int get length

The number of bytes in this builder.

isEmptygetter
bool get isEmpty

Whether the buffer is empty.

bool get isNotEmpty

Whether the buffer is non-empty.

Methods

addmethod
void add(List<int> bytes)

Appends bytes to the current contents of this builder.

Each value of bytes will be truncated to an 8-bit value in the range 0.. 255.

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

void main() {
  final b = BytesBuilder();
  b.add(utf8.encode('GET / HTTP/1.1'));
  b.add([13, 10]);
  print('${b.length} bytes, ends with CRLF: ${b.toBytes().sublist(b.length - 2)}');
}
Output
16 bytes, ends with CRLF: [13, 10]
addBytemethod
void addByte(int byte)

Appends byte to the current contents of this builder.

The byte will be truncated to an 8-bit value in the range 0.. 255.

Example
import 'raya:io';

void main() {
  final b = BytesBuilder();
  for (var i = 0; i < 5; i++) {
    b.addByte(i * i);
  }
  b.addByte(256 + 7); // only the low 8 bits are kept
  print(b.toBytes());
}
Output
[0, 1, 4, 9, 16, 7]
takeBytesmethod
Uint8List takeBytes()

Returns the bytes currently contained in this builder and clears it.

The returned list may be a view of a larger buffer.

Example
import 'raya:io';

void main() {
  final b = BytesBuilder()..add([1, 2, 3]);
  final taken = b.takeBytes();
  print('taken: $taken, builder now empty: ${b.isEmpty}');
}
Output
taken: [1, 2, 3], builder now empty: true
toBytesmethod
Uint8List toBytes()

Returns a copy of the current byte contents of this builder.

Leaves the contents of this builder intact.

Example
import 'raya:io';

void main() {
  final b = BytesBuilder()..add([7, 8]);
  final copy = b.toBytes();
  b.addByte(9);
  print('snapshot: $copy, builder: ${b.toBytes()}');
}
Output
snapshot: [7, 8], builder: [7, 8, 9]
clearmethod
void clear()

Clears the contents of this builder.

The current contents are discarded and this builder becomes empty.

Example
import 'raya:io';

void main() {
  final b = BytesBuilder()..add([1, 2, 3]);
  b.clear();
  print('after clear: length ${b.length}');
  b.addByte(42);
  print('reused: ${b.toBytes()}');
}
Output
after clear: length 0
reused: [42]
abstract class HttpStatus

HTTP status codes. Exported in raya:io and raya:html.

Static

continue_constant
static const int continue_ = 100
static const int switchingProtocols = 101
processingconstant
static const int processing = 102
okconstant
static const int ok = 200
createdconstant
static const int created = 201
acceptedconstant
static const int accepted = 202
static const int nonAuthoritativeInformation = 203
noContentconstant
static const int noContent = 204
resetContentconstant
static const int resetContent = 205
static const int partialContent = 206
multiStatusconstant
static const int multiStatus = 207
static const int alreadyReported = 208
imUsedconstant
static const int imUsed = 226
static const int multipleChoices = 300
static const int movedPermanently = 301
foundconstant
static const int found = 302
static const int movedTemporarily = 302
seeOtherconstant
static const int seeOther = 303
notModifiedconstant
static const int notModified = 304
useProxyconstant
static const int useProxy = 305
static const int temporaryRedirect = 307
static const int permanentRedirect = 308
badRequestconstant
static const int badRequest = 400
unauthorizedconstant
static const int unauthorized = 401
static const int paymentRequired = 402
forbiddenconstant
static const int forbidden = 403
notFoundconstant
static const int notFound = 404
static const int methodNotAllowed = 405
static const int notAcceptable = 406
static const int proxyAuthenticationRequired = 407
static const int requestTimeout = 408
conflictconstant
static const int conflict = 409
goneconstant
static const int gone = 410
static const int lengthRequired = 411
static const int preconditionFailed = 412
static const int requestEntityTooLarge = 413
static const int requestUriTooLong = 414
static const int unsupportedMediaType = 415
static const int requestedRangeNotSatisfiable = 416
static const int expectationFailed = 417
static const int misdirectedRequest = 421
static const int unprocessableEntity = 422
lockedconstant
static const int locked = 423
static const int failedDependency = 424
static const int upgradeRequired = 426
static const int preconditionRequired = 428
static const int tooManyRequests = 429
static const int requestHeaderFieldsTooLarge = 431
static const int connectionClosedWithoutResponse = 444
static const int unavailableForLegalReasons = 451
static const int clientClosedRequest = 499
static const int internalServerError = 500
static const int notImplemented = 501
badGatewayconstant
static const int badGateway = 502
static const int serviceUnavailable = 503
static const int gatewayTimeout = 504
static const int httpVersionNotSupported = 505
static const int variantAlsoNegotiates = 506
static const int insufficientStorage = 507
loopDetectedconstant
static const int loopDetected = 508
notExtendedconstant
static const int notExtended = 510
static const int networkAuthenticationRequired = 511
static const int networkConnectTimeoutError = 599
CONTINUEconstantdeprecated
static const int CONTINUE = continue_
SWITCHING_PROTOCOLSconstantdeprecated
static const int SWITCHING_PROTOCOLS = switchingProtocols
OKconstantdeprecated
static const int OK = ok
CREATEDconstantdeprecated
static const int CREATED = created
ACCEPTEDconstantdeprecated
static const int ACCEPTED = accepted
static const int NON_AUTHORITATIVE_INFORMATION = nonAuthoritativeInformation
NO_CONTENTconstantdeprecated
static const int NO_CONTENT = noContent
RESET_CONTENTconstantdeprecated
static const int RESET_CONTENT = resetContent
PARTIAL_CONTENTconstantdeprecated
static const int PARTIAL_CONTENT = partialContent
MULTIPLE_CHOICESconstantdeprecated
static const int MULTIPLE_CHOICES = multipleChoices
MOVED_PERMANENTLYconstantdeprecated
static const int MOVED_PERMANENTLY = movedPermanently
FOUNDconstantdeprecated
static const int FOUND = found
MOVED_TEMPORARILYconstantdeprecated
static const int MOVED_TEMPORARILY = movedTemporarily
SEE_OTHERconstantdeprecated
static const int SEE_OTHER = seeOther
NOT_MODIFIEDconstantdeprecated
static const int NOT_MODIFIED = notModified
USE_PROXYconstantdeprecated
static const int USE_PROXY = useProxy
TEMPORARY_REDIRECTconstantdeprecated
static const int TEMPORARY_REDIRECT = temporaryRedirect
BAD_REQUESTconstantdeprecated
static const int BAD_REQUEST = badRequest
UNAUTHORIZEDconstantdeprecated
static const int UNAUTHORIZED = unauthorized
PAYMENT_REQUIREDconstantdeprecated
static const int PAYMENT_REQUIRED = paymentRequired
FORBIDDENconstantdeprecated
static const int FORBIDDEN = forbidden
NOT_FOUNDconstantdeprecated
static const int NOT_FOUND = notFound
METHOD_NOT_ALLOWEDconstantdeprecated
static const int METHOD_NOT_ALLOWED = methodNotAllowed
NOT_ACCEPTABLEconstantdeprecated
static const int NOT_ACCEPTABLE = notAcceptable
static const int PROXY_AUTHENTICATION_REQUIRED = proxyAuthenticationRequired
REQUEST_TIMEOUTconstantdeprecated
static const int REQUEST_TIMEOUT = requestTimeout
CONFLICTconstantdeprecated
static const int CONFLICT = conflict
GONEconstantdeprecated
static const int GONE = gone
LENGTH_REQUIREDconstantdeprecated
static const int LENGTH_REQUIRED = lengthRequired
PRECONDITION_FAILEDconstantdeprecated
static const int PRECONDITION_FAILED = preconditionFailed
REQUEST_ENTITY_TOO_LARGEconstantdeprecated
static const int REQUEST_ENTITY_TOO_LARGE = requestEntityTooLarge
REQUEST_URI_TOO_LONGconstantdeprecated
static const int REQUEST_URI_TOO_LONG = requestUriTooLong
UNSUPPORTED_MEDIA_TYPEconstantdeprecated
static const int UNSUPPORTED_MEDIA_TYPE = unsupportedMediaType
static const int REQUESTED_RANGE_NOT_SATISFIABLE = requestedRangeNotSatisfiable
EXPECTATION_FAILEDconstantdeprecated
static const int EXPECTATION_FAILED = expectationFailed
UPGRADE_REQUIREDconstantdeprecated
static const int UPGRADE_REQUIRED = upgradeRequired
INTERNAL_SERVER_ERRORconstantdeprecated
static const int INTERNAL_SERVER_ERROR = internalServerError
NOT_IMPLEMENTEDconstantdeprecated
static const int NOT_IMPLEMENTED = notImplemented
BAD_GATEWAYconstantdeprecated
static const int BAD_GATEWAY = badGateway
SERVICE_UNAVAILABLEconstantdeprecated
static const int SERVICE_UNAVAILABLE = serviceUnavailable
GATEWAY_TIMEOUTconstantdeprecated
static const int GATEWAY_TIMEOUT = gatewayTimeout
HTTP_VERSION_NOT_SUPPORTEDconstantdeprecated
static const int HTTP_VERSION_NOT_SUPPORTED = httpVersionNotSupported
static const int NETWORK_CONNECT_TIMEOUT_ERROR = networkConnectTimeoutError