Socket abstract class
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.
abstract class Socket implements Stream<List<int>>, IOSink {
/**
* 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.
*/
external static Future<Socket> connect(host, int port);
/**
* 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.
*/
void destroy();
/**
* Use [setOption] to customize the [RawSocket]. See [SocketOption] for
* available options.
*
* Returns [true] if the option was set successfully, false otherwise.
*/
bool setOption(SocketOption option, bool enabled);
/**
* Returns the port used by this socket.
*/
int get port;
/**
* Returns the remote port connected to by this socket.
*/
int get remotePort;
/**
* Returns the [InternetAddress] used to connect this socket.
*/
InternetAddress get address;
/**
* Returns the remote host connected to by this socket.
*/
String get remoteHost;
}
Subclasses
Implements
Static Methods
Future<Socket> connect(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.
external static Future<Socket> connect(host, int port);
Properties
final InternetAddress address #
Returns the InternetAddress used to connect this socket.
InternetAddress get address;
final Future 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.
Future get done;
Encoding encoding #
The Encoding used when writing strings. Depending on the underlying consumer this property might be mutable.
Encoding encoding
final Future<T> first #
Returns the first element.
If this is empty throws a StateError. Otherwise this method is
equivalent to this.elementAt(0)
Future<T> get first {
_FutureImpl<T> future = new _FutureImpl<T>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
subscription.cancel();
future._setValue(value);
return;
},
onError: future._setError,
onDone: () {
future._setError(new StateError("No elements"));
},
cancelOnError: true);
return future;
}
final bool isBroadcast #
Reports whether this stream is a broadcast stream.
bool get isBroadcast => false;
final Future<bool> isEmpty #
Reports whether this stream contains any elements.
Future<bool> get isEmpty {
_FutureImpl<bool> future = new _FutureImpl<bool>();
StreamSubscription subscription;
subscription = this.listen(
(_) {
subscription.cancel();
future._setValue(false);
},
onError: future._setError,
onDone: () {
future._setValue(true);
},
cancelOnError: true);
return future;
}
final Future<T> last #
Returns the last element.
If this is empty throws a StateError.
Future<T> get last {
_FutureImpl<T> future = new _FutureImpl<T>();
T result = null;
bool foundResult = false;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
foundResult = true;
result = value;
},
onError: future._setError,
onDone: () {
if (foundResult) {
future._setValue(result);
return;
}
future._setError(new StateError("No elements"));
},
cancelOnError: true);
return future;
}
final Future<int> length #
Counts the elements in the stream.
Future<int> get length {
_FutureImpl<int> future = new _FutureImpl<int>();
int count = 0;
this.listen(
(_) { count++; },
onError: future._setError,
onDone: () {
future._setValue(count);
},
cancelOnError: true);
return future;
}
final String remoteHost #
Returns the remote host connected to by this socket.
String get remoteHost;
final Future<T> single #
Returns the single element.
If this is empty or has more than one element throws a StateError.
Future<T> get single {
_FutureImpl<T> future = new _FutureImpl<T>();
T result = null;
bool foundResult = false;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
if (foundResult) {
subscription.cancel();
// This is the second element we get.
Error error = new StateError("More than one element");
future._setError(error);
return;
}
foundResult = true;
result = value;
},
onError: future._setError,
onDone: () {
if (foundResult) {
future._setValue(result);
return;
}
future._setError(new StateError("No elements"));
},
cancelOnError: true);
return future;
}
Methods
abstract void add(List<int> data) #
Writes the bytes uninterpreted to the consumer.
abstract Future addStream(Stream<List<int>> stream) #
Adds all elements of the given
stream to this.
Future<bool> any(bool test(T element)) #
Checks whether test accepts any element provided by this stream.
Completes the Future when the answer is known.
If this stream reports an error, the Future will report that error.
Future<bool> any(bool test(T element)) {
_FutureImpl<bool> future = new _FutureImpl<bool>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ element) {
_runUserCode(
() => test(element),
(bool isMatch) {
if (isMatch) {
subscription.cancel();
future._setValue(true);
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
future._setValue(false);
},
cancelOnError: true);
return future;
}
Stream<T> asBroadcastStream() #
Returns a multi-subscription stream that produces the same events as this.
If this stream is single-subscription, return a new stream that allows multiple subscribers. It will subscribe to this stream when its first subscriber is added, and unsubscribe again when the last subscription is canceled.
If this stream is already a broadcast stream, it is returned unmodified.
Stream<T> asBroadcastStream() {
if (isBroadcast) return this;
return new _AsBroadcastStream<T>(this);
}
Future<bool> contains(T match) #
Checks whether match occurs in the elements provided by this stream.
Completes the Future when the answer is known.
If this stream reports an error, the Future will report that error.
Future<bool> contains(T match) {
_FutureImpl<bool> future = new _FutureImpl<bool>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ element) {
_runUserCode(
() => (element == match),
(bool isMatch) {
if (isMatch) {
subscription.cancel();
future._setValue(true);
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
future._setValue(false);
},
cancelOnError: true);
return future;
}
abstract void destroy() #
Stream<T> distinct([bool equals(T previous, T next)]) #
Skips data events if they are equal to the previous data event.
The returned stream provides the same events as this stream, except that it never provides two consequtive data events that are equal.
Equality is determined by the provided equals method. If that is omitted, the '==' operator on the last provided data element is used.
Stream<T> distinct([bool equals(T previous, T next)]) {
return new _DistinctStream(this, equals);
}
Future drain([futureValue]) #
Discards all data on the stream, but signals when it's done or an error occured.
When subscribing using drain, cancelOnError will be true. This means
that the future will complete with the first error on the stream and then
cancel the subscription.
In case of a done event the future completes with the given
futureValue.
Future drain([var futureValue]) => listen(null, cancelOnError: true) .asFuture(futureValue);
Future<T> elementAt(int index) #
Returns the value of the indexth data event of this stream.
If an error event occurs, the future will end with this error.
If this stream provides fewer than index elements before closing, an error is reported.
Future<T> elementAt(int index) {
if (index is! int || index < 0) throw new ArgumentError(index);
_FutureImpl<T> future = new _FutureImpl<T>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
if (index == 0) {
subscription.cancel();
future._setValue(value);
return;
}
index -= 1;
},
onError: future._setError,
onDone: () {
future._setError(new StateError("Not enough elements for elementAt"));
},
cancelOnError: true);
return future;
}
Future<bool> every(bool test(T element)) #
Checks whether test accepts all elements provided by this stream.
Completes the Future when the answer is known.
If this stream reports an error, the Future will report that error.
Future<bool> every(bool test(T element)) {
_FutureImpl<bool> future = new _FutureImpl<bool>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ element) {
_runUserCode(
() => test(element),
(bool isMatch) {
if (!isMatch) {
subscription.cancel();
future._setValue(false);
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
future._setValue(true);
},
cancelOnError: true);
return future;
}
Stream expand(Iterable convert(T value)) #
Creates a new stream from this stream that converts each element into zero or more events.
Each incoming event is converted to an Iterable of new events,
and each of these new events are then sent by the returned stream
in order.
Stream expand(Iterable convert(T value)) {
return new _ExpandStream<T, dynamic>(this, convert);
}
Future<T> firstWhere(bool test(T element), {T defaultValue()}) #
Finds the first element of this stream matching test.
Returns a future that is filled with the first element of this stream that test returns true for.
If no such element is found before this stream is done, and a defaultValue function is provided, the result of calling defaultValue becomes the value of the future.
If an error occurs, or if this stream ends without finding a match and with no defaultValue function provided, the future will receive an error.
Future<T> firstWhere(bool test(T element), {T defaultValue()}) {
_FutureImpl<T> future = new _FutureImpl<T>();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
_runUserCode(
() => test(value),
(bool isMatch) {
if (isMatch) {
subscription.cancel();
future._setValue(value);
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
if (defaultValue != null) {
_runUserCode(defaultValue, future._setValue, future._setError);
return;
}
future._setError(new StateError("firstMatch ended without match"));
},
cancelOnError: true);
return future;
}
Future fold(initialValue, combine(previous, T element)) #
Reduces a sequence of values by repeatedly applying combine.
Future fold(var initialValue, combine(var previous, T element)) {
_FutureImpl result = new _FutureImpl();
var value = initialValue;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ element) {
_runUserCode(
() => combine(value, element),
(newValue) { value = newValue; },
_cancelAndError(subscription, result)
);
},
onError: (e) {
result._setError(e);
},
onDone: () {
result._setValue(value);
},
cancelOnError: true);
return result;
}
Future forEach(void action(T element)) #
Executes action on each data event of the stream.
Completes the returned Future when all events of the stream
have been processed. Completes the future with an error if the
stream has an error event, or if
action throws.
Future forEach(void action(T element)) {
_FutureImpl future = new _FutureImpl();
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ element) {
_runUserCode(
() => action(element),
(_) {},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
future._setValue(null);
},
cancelOnError: true);
return future;
}
Stream<T> handleError(void handle(error), {bool test(error)}) #
Creates a wrapper Stream that intercepts some errors from this stream.
If this stream sends an error that matches test, then it is intercepted by the handle function.
An [AsyncError] [:e:] is matched by a test function if test(e) returns
true. If
test is omitted, every error is considered matching.
If the error is intercepted, the handle function can decide what to do with it. It can throw if it wants to raise a new (or the same) error, or simply return to make the stream forget the error.
If you need to transform an error into a data event, use the more generic
Stream.transformEvent to handle the event by writing a data event to
the output sink
Stream<T> handleError(void handle( error), { bool test(error) }) {
return new _HandleErrorStream<T>(this, handle, test);
}
Future<T> lastWhere(bool test(T element), {T defaultValue()}) #
Finds the last element in this stream matching test.
As firstWhere, except that the last matching element is found.
That means that the result cannot be provided before this stream
is done.
Future<T> lastWhere(bool test(T element), {T defaultValue()}) {
_FutureImpl<T> future = new _FutureImpl<T>();
T result = null;
bool foundResult = false;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
_runUserCode(
() => true == test(value),
(bool isMatch) {
if (isMatch) {
foundResult = true;
result = value;
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
if (foundResult) {
future._setValue(result);
return;
}
if (defaultValue != null) {
_runUserCode(defaultValue, future._setValue, future._setError);
return;
}
future._setError(new StateError("lastMatch ended without match"));
},
cancelOnError: true);
return future;
}
abstract StreamSubscription<T> listen(void onData(T event), {void onError(error), void 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.
Stream map(convert(T event)) #
Creates a new stream that converts each element of this stream to a new value using the convert function.
Stream map(convert(T event)) {
return new _MapStream<T, dynamic>(this, convert);
}
Future pipe(StreamConsumer<T> streamConsumer) #
Binds this stream as the input of the provided StreamConsumer.
Future pipe(StreamConsumer<T> streamConsumer) {
return streamConsumer.addStream(this).then((_) => streamConsumer.close());
}
Future<T> reduce(T combine(T previous, T element)) #
Reduces a sequence of values by repeatedly applying combine.
Future<T> reduce(T combine(T previous, T element)) {
_FutureImpl<T> result = new _FutureImpl<T>();
bool seenFirst = false;
T value;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/* T */ element) {
if (seenFirst) {
_runUserCode(() => combine(value, element),
(T newValue) { value = newValue; },
_cancelAndError(subscription, result));
} else {
value = element;
seenFirst = true;
}
},
onError: result._setError,
onDone: () {
if (!seenFirst) {
result._setError(new StateError("No elements"));
} else {
result._setValue(value);
}
},
cancelOnError: true
);
return result;
}
abstract 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.
Future<T> singleWhere(bool test(T element)) #
Finds the single element in this stream matching test.
Like lastMatch, except that it is an error if more than one
matching element occurs in the stream.
Future<T> singleWhere(bool test(T element)) {
_FutureImpl<T> future = new _FutureImpl<T>();
T result = null;
bool foundResult = false;
StreamSubscription subscription;
subscription = this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ value) {
_runUserCode(
() => true == test(value),
(bool isMatch) {
if (isMatch) {
if (foundResult) {
subscription.cancel();
future._setError(
new StateError('Multiple matches for "single"'));
return;
}
foundResult = true;
result = value;
}
},
_cancelAndError(subscription, future)
);
},
onError: future._setError,
onDone: () {
if (foundResult) {
future._setValue(result);
return;
}
future._setError(new StateError("single ended without match"));
},
cancelOnError: true);
return future;
}
Stream<T> skip(int count) #
Skips the first count data events from this stream.
Stream<T> skip(int count) {
return new _SkipStream(this, count);
}
Stream<T> skipWhile(bool test(T element)) #
Skip data events from this stream while they are matched by test.
Error and done events are provided by the returned stream unmodified.
Starting with the first data event where test returns true for the event data, the returned stream will have the same events as this stream.
Stream<T> skipWhile(bool test(T element)) {
return new _SkipWhileStream(this, test);
}
Stream<T> take(int count) #
Provides at most the first n values of this stream.
Forwards the first n data events of this stream, and all error
events, to the returned stream, and ends with a done event.
If this stream produces fewer than count values before it's done, so will the returned stream.
Stream<T> take(int count) {
return new _TakeStream(this, count);
}
Stream<T> takeWhile(bool test(T element)) #
Forwards data events while test is successful.
The returned stream provides the same events as this stream as long
as
test returns true for the event data. The stream is done
when either this stream is done, or when this stream first provides
a value that
test doesn't accept.
Stream<T> takeWhile(bool test(T element)) {
return new _TakeWhileStream(this, test);
}
Future<List<T>> toList() #
Collects the data of this stream in a List.
Future<List<T>> toList() {
List<T> result = <T>[];
_FutureImpl<List<T>> future = new _FutureImpl<List<T>>();
this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ data) {
result.add(data);
},
onError: future._setError,
onDone: () {
future._setValue(result);
},
cancelOnError: true);
return future;
}
Future<Set<T>> toSet() #
Collects the data of this stream in a Set.
Future<Set<T>> toSet() {
Set<T> result = new Set<T>();
_FutureImpl<Set<T>> future = new _FutureImpl<Set<T>>();
this.listen(
// TODO(ahe): Restore type when feature is implemented in dart2js
// checked mode. http://dartbug.com/7733
(/*T*/ data) {
result.add(data);
},
onError: future._setError,
onDone: () {
future._setValue(result);
},
cancelOnError: true);
return future;
}
Stream transform(StreamTransformer<T, dynamic> streamTransformer) #
Chains this stream as the input of the provided StreamTransformer.
Returns the result of streamTransformer.bind itself.
Stream transform(StreamTransformer<T, dynamic> streamTransformer) {
return streamTransformer.bind(this);
}
Stream<T> where(bool test(T event)) #
Creates a new stream from this stream that discards some data events.
The new stream sends the same error and done events as this stream, but it only sends the data events that satisfy the test.
Stream<T> where(bool test(T event)) {
return new _WhereStream<T>(this, test);
}
abstract void write(Object obj) #
Converts
obj to a String by invoking toString and adds the result to
this.
abstract void writeAll(Iterable objects, [String separator = ""]) #
Iterates over the given
objects and writes them in sequence.
abstract void writeCharCode(int charCode) #
Writes the
charCode to this.
This method is equivalent to write(new String.fromCharCode(charCode)).
abstract void writeln([Object obj = ""]) #
Converts
obj to a String by invoking toString and adds the result to
this. Then adds a new line.