WebSocket
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
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.
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);
}101: hello over a hand-made upgrade
Static
static const int open = 1static const int closing = 2static const int closed = 3static 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:
connectionsec-websocket-keysec-websocket-protocolsec-websocket-versionupgrade
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.
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);
}protocol chosen: chat.v2 client sees protocol chat.v2
static String? get userAgentGets the user agent used for WebSocket connections.
static set userAgent(String? userAgent)Sets the user agent to use for WebSocket connections.
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);
}user agent: raya-ws-example/1.0
Properties
Duration? pingIntervalThe 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.
String get extensionsThe extensions property is initially the empty string. After the WebSocket connection is established this string reflects the extensions used by the server.
String? get protocolThe 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:].
int? get closeCodeThe close code set when the WebSocket connection is closed. If there is no close code available this property will be [:null:]
String? get closeReasonThe close reason set when the WebSocket connection is closed. If there is no close reason available this property will be [:null:]
Methods
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.
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);
}client closed, readyState 1 server saw close code 1000, reason "bye"
void add(data)Sends data on the WebSocket connection. The data in data must be either a String, or a List<int> holding bytes.
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);
}[text: hi, binary: [1, 2, 3]]
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.
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.
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);
}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.
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);
}String: déjà vu
WebSocketException
class WebSocketException implements IOException
Constructors
const WebSocketException([this.message = "", this.httpStatusCode])import 'raya:io';
void main() {
const e = WebSocketException('Connection was not upgraded to websocket', 404);
print('message: ${e.message}, http status: ${e.httpStatusCode}');
}message: Connection was not upgraded to websocket, http status: 404
Properties
final String messagefinal int? httpStatusCodeMethods
String toString()import 'raya:io';
void main() {
print(const WebSocketException('Protocol error'));
}WebSocketException: Protocol error
BytesBuilder
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.)
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()}');
}length 3, bytes [1, 2, 3]
Properties
Methods
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.
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)}');
}16 bytes, ends with CRLF: [13, 10]
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.
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());
}[0, 1, 4, 9, 16, 7]
Uint8List takeBytes()Returns the bytes currently contained in this builder and clears it.
The returned list may be a view of a larger buffer.
import 'raya:io';
void main() {
final b = BytesBuilder()..add([1, 2, 3]);
final taken = b.takeBytes();
print('taken: $taken, builder now empty: ${b.isEmpty}');
}taken: [1, 2, 3], builder now empty: true
Uint8List toBytes()Returns a copy of the current byte contents of this builder.
Leaves the contents of this builder intact.
import 'raya:io';
void main() {
final b = BytesBuilder()..add([7, 8]);
final copy = b.toBytes();
b.addByte(9);
print('snapshot: $copy, builder: ${b.toBytes()}');
}snapshot: [7, 8], builder: [7, 8, 9]
void clear()Clears the contents of this builder.
The current contents are discarded and this builder becomes empty.
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()}');
}after clear: length 0 reused: [42]
HttpStatus
abstract class HttpStatus
HTTP status codes. Exported in raya:io and raya:html.
Static
static const int continue_ = 100static const int switchingProtocols = 101static const int processing = 102static const int ok = 200static const int created = 201static const int accepted = 202static const int nonAuthoritativeInformation = 203static const int noContent = 204static const int resetContent = 205static const int partialContent = 206static const int multiStatus = 207static const int alreadyReported = 208static const int imUsed = 226static const int multipleChoices = 300static const int movedPermanently = 301static const int found = 302static const int movedTemporarily = 302static const int seeOther = 303static const int notModified = 304static const int useProxy = 305static const int temporaryRedirect = 307static const int permanentRedirect = 308static const int badRequest = 400static const int unauthorized = 401static const int paymentRequired = 402static const int forbidden = 403static const int notFound = 404static const int methodNotAllowed = 405static const int notAcceptable = 406static const int proxyAuthenticationRequired = 407static const int requestTimeout = 408static const int conflict = 409static const int gone = 410static const int lengthRequired = 411static const int preconditionFailed = 412static const int requestEntityTooLarge = 413static const int requestUriTooLong = 414static const int unsupportedMediaType = 415static const int requestedRangeNotSatisfiable = 416static const int expectationFailed = 417static const int misdirectedRequest = 421static const int unprocessableEntity = 422static const int locked = 423static const int failedDependency = 424static const int upgradeRequired = 426static const int preconditionRequired = 428static const int tooManyRequests = 429static const int requestHeaderFieldsTooLarge = 431static const int connectionClosedWithoutResponse = 444static const int clientClosedRequest = 499static const int internalServerError = 500static const int notImplemented = 501static const int badGateway = 502static const int gatewayTimeout = 504static const int httpVersionNotSupported = 505static const int variantAlsoNegotiates = 506static const int insufficientStorage = 507static const int loopDetected = 508static const int notExtended = 510static const int networkAuthenticationRequired = 511static const int networkConnectTimeoutError = 599static const int CONTINUE = continue_static const int SWITCHING_PROTOCOLS = switchingProtocolsstatic const int OK = okstatic const int CREATED = createdstatic const int ACCEPTED = acceptedstatic const int NON_AUTHORITATIVE_INFORMATION = nonAuthoritativeInformationstatic const int NO_CONTENT = noContentstatic const int RESET_CONTENT = resetContentstatic const int PARTIAL_CONTENT = partialContentstatic const int MULTIPLE_CHOICES = multipleChoicesstatic const int MOVED_PERMANENTLY = movedPermanentlystatic const int FOUND = foundstatic const int MOVED_TEMPORARILY = movedTemporarilystatic const int SEE_OTHER = seeOtherstatic const int NOT_MODIFIED = notModifiedstatic const int USE_PROXY = useProxystatic const int TEMPORARY_REDIRECT = temporaryRedirectstatic const int BAD_REQUEST = badRequeststatic const int UNAUTHORIZED = unauthorizedstatic const int PAYMENT_REQUIRED = paymentRequiredstatic const int FORBIDDEN = forbiddenstatic const int NOT_FOUND = notFoundstatic const int METHOD_NOT_ALLOWED = methodNotAllowedstatic const int NOT_ACCEPTABLE = notAcceptablestatic const int PROXY_AUTHENTICATION_REQUIRED = proxyAuthenticationRequiredstatic const int REQUEST_TIMEOUT = requestTimeoutstatic const int CONFLICT = conflictstatic const int GONE = gonestatic const int LENGTH_REQUIRED = lengthRequiredstatic const int PRECONDITION_FAILED = preconditionFailedstatic const int REQUEST_ENTITY_TOO_LARGE = requestEntityTooLargestatic const int REQUEST_URI_TOO_LONG = requestUriTooLongstatic const int UNSUPPORTED_MEDIA_TYPE = unsupportedMediaTypestatic const int REQUESTED_RANGE_NOT_SATISFIABLE = requestedRangeNotSatisfiablestatic const int EXPECTATION_FAILED = expectationFailedstatic const int UPGRADE_REQUIRED = upgradeRequiredstatic const int INTERNAL_SERVER_ERROR = internalServerErrorstatic const int NOT_IMPLEMENTED = notImplementedstatic const int BAD_GATEWAY = badGatewaystatic const int SERVICE_UNAVAILABLE = serviceUnavailablestatic const int GATEWAY_TIMEOUT = gatewayTimeoutstatic const int HTTP_VERSION_NOT_SUPPORTED = httpVersionNotSupportedstatic const int NETWORK_CONNECT_TIMEOUT_ERROR = networkConnectTimeoutError