Standard Library
interface INet
What a program may do with the network: open connections and listen for them.
since 0.1.0-alpha.1linuxwindowswasm
Overview
A function that takes an INet parameter does not open real sockets directly, so a test can
pass an implementation that fails or answers on demand. use std::INet; makes the real
network (SystemNet) the default for such parameters.
Examples
class Offline : INet {
TcpStream? connect(string host, int port) => None;
TcpListener listen(int port) {
throw RuntimeException("offline: cannot listen on ${port}");
}
}
void probe(INet net) {
TcpStream? s = net.connect("example.org", 80);
console.writeln(s == None ? "connect failed" : "connected");
try {
net.listen(8080);
} catch (RuntimeException e) {
console.writeln(e.message);
}
}
bind INet => Offline();
probe();
connect failed
offline: cannot listen on 8080
Methods
connect
connect(string host, int port) -> TcpStream | NoneOpen a connection to a host and port.
Parameters
- host
- The host name or address.
- port
- The port number.
Returns
The connected stream, or None when the connection fails.
Examples
class Refusing : INet {
TcpStream? connect(string host, int port) => None;
TcpListener listen(int port) {
throw RuntimeException("not supported");
}
}
INet net = Refusing();
console.writeln(net.connect("example.org", 80) == None);
true
listen
listen(int port) -> TcpListenerStart listening for connections on a port.
The caller checks ok() on the result to see whether the port could be bound.
Parameters
- port
- The port number to listen on.
Returns
The listener.
Examples
class Closed : INet {
TcpStream? connect(string host, int port) => None;
TcpListener listen(int port) {
throw RuntimeException("closed: cannot listen on ${port}");
}
}
INet net = Closed();
try {
net.listen(9000);
} catch (RuntimeException e) {
console.writeln(e.message);
}
closed: cannot listen on 9000