Skip to content

Core\Http\Client::openSocket

Opens a WebSocket connection to another server, so your program can send and receive messages while the connection stays open.

A normal HTTP request gets one response, and then it is finished. A WebSocket stays open. send and sendBytes write a message, receive returns the next message from the other server, and close ends the connection. When the other server closes it, receive returns null.

The URL must start with ws:// or wss://. Any public host is allowed, unless net.connect in [capabilities.net] in nvs.toml lists the allowed hosts. An address inside your own network throws a RuntimeError. Loopback (127.0.0.1) is allowed only from the command line and in development mode. idle is how long the connection may stay quiet, maxDuration is how long it may stay open, and maxMessage is the largest message in bytes.

Good to know: the connection is closed when the request, command or job that opened it ends.

The examples below run without a network, so every connection in them fails before it opens. They show a refused address, the checks on the URL and the options, and a price feed with a fallback.

Parameters

  • $urlstring|Core\Http\TargetThe server to open the socket to. It is a ws or wss URL that the program wrote, or a Core\Http\Target from Core\Http::allowUrl. An http or https URL is not allowed here. A tainted URL comes from outside the program, such as from a request. Check it with Core\Http::allowUrl first.

Options

  • deadlineCore\Time\DurationoptionalThe time limit for the opening handshake. It covers the connection and every address tried, and it ends when the 101 reply arrives. After that, idle and maxDuration limit the conversation. If it is not given, the runtime's [http.client] deadline is used. There is no way to write a socket with no deadline.
  • connectTimeoutCore\Time\DurationoptionalHow long the connection alone may take. This time is part of deadline, and is not added to it.
  • headersarray<secret string>optionalExtra request headers, by name. A secret value is a value the program must keep hidden, such as an API key. It is allowed here, because a credential must reach the API it is for. A tainted value is not allowed. The runtime adds its own headers as well.
  • identityCore\Http\IdentityoptionalThe client certificate to send when the server asks for one. Create it with Core\Http\Identity::read. Nothing is sent to a server that does not ask. Two different identities never share a pooled connection. A call without an identity does not share one with a call that has one.
  • tlsCastringoptionalThe PEM certificates to trust for this call. They replace [tls.client] roots certificates. The URL's host must be in the anchors grant of capabilities.tls. If it is not, the call throws an error before it connects.
  • tlsPinstring|array<string>optionalOne sha256//<base64> public-key pin, or several. The server is accepted if the hash of its SubjectPublicKeyInfo matches one of them. No certificate chain is checked. Use this to reach a server with a self-signed certificate. The host must be in the pin grant.
  • tlsVerifyHostbooloptionalIf it is false, the chain is still checked, and only the name check is skipped. The host must be in the any_name grant.
  • tlsVerifybooloptionalIf it is false, neither the chain nor the name is checked. The handshake signature is still checked, so the server has the key it sent. But nothing shows whose key it is. The host must be in the insecure grant.
  • tlsMinVersionstringoptionalThe lowest TLS version this call allows, "1.2" or "1.3". It needs no grant, because it can only make the call stricter. A value below the runtime's [tls.client] min_version throws an error.
  • connectTostringoptionalThe IP address to connect to. The URL's host is not looked up, but the certificate is still checked against that host. The host must be in the net.connect_to grant. The deployment's address policy checks this address like a looked-up one. With a Core\Http\Target as the URL, this option throws an error, because the target already has its approved addresses.
  • protocolsarray<string>optionalThe subprotocols to offer in Sec-WebSocket-Protocol, most preferred first. Each name is one word of letters, digits and the punctuation an HTTP token allows, such as ., - and _. A space, a comma or a control character throws an error. Core\Http\Socket::protocol returns the one the server chooses. If the server chooses a name that was not offered, the call throws an error.
  • idleCore\Time\DurationoptionalThe longest time the socket may be silent in either direction. If it is not given, the runtime's [http.client] idle is used. There is no way to turn this limit off. With ping set, a live but quiet server answers the pings, so only a dead server reaches this limit.
  • maxDurationCore\Time\DurationoptionalThe longest time the socket may stay open in total. This limit stops a server that sends one frame at a time, just often enough to pass the idle check. If it is not given, the runtime's [http.client] max_duration is used.
  • maxMessageuintoptionalThe largest message, in bytes, that this side builds from the server's fragments. A larger message closes the socket with code 1009. The waiting receive then throws an error that names the limit. If it is not given, the runtime's [http.client.socket] max_message is used.
  • sendTimeoutCore\Time\DurationoptionalThe longest time a frame may wait to be sent to a server that is not reading. It is also how long close waits for the server's own close frame. If it is not given, the runtime's [http.client.socket] send_timeout is used.
  • pingCore\Time\DurationoptionalHow long the socket stays silent before it sends a ping. A live server answers the ping, so idle closes only a dead connection. If it is not given, no ping is sent, because a ping is traffic the server did not ask for. A ping from the server is always answered, because the WebSocket protocol requires it.

Return value

Returns Core\Http\Socket. A Core\Http\Socket for the conversation. receive() returns the server's next message as a Core\Socket\Message, the same class a server-side connection uses. send() and sendBytes() send the two kinds of message, and close() ends the conversation. The socket belongs to the task that opened it. It is closed with code 1001 when that task ends, so it never lives longer than its request, command or job.

Errors

  • RuntimeErrorThe URL is not allowed. It is not a URL, its scheme is not ws or wss, or it has no host. This method does not accept http or https, and the other methods do not accept ws or wss. Or net.connect does not grant the host, or the host resolves to an address the deployment's policy denies. An option is out of range. A deadline, connectTimeout, idle, maxDuration, sendTimeout or ping is not a positive duration. Or a protocols entry is not one word. Or the server did not open a socket. It sent a redirect, which is never followed, and the message names its Location. Or it sent a status other than 101. Or it chose a subprotocol that protocols did not offer.

Examples

The examples below run with this configuration file.

nvs.toml
# The program may connect to public hosts only.
# `internal = []` allows no address on this computer or on a private network.
[capabilities.net]
internal = []

Connecting to a chat service

<?nvs
// Shows how to open a WebSocket to another server, and what happens when the
// address is inside your own network.
// `Core\Http\Client::openSocket` opens the connection and returns a `Core\Http\Socket`.
// 10.0.0.7 is a private address, so the call throws a `RuntimeError` before it connects.
try {
Core\Http\Socket $socket = Core\Http\Client::openSocket('wss://10.0.0.7/chat');
$socket->send('hello');
var $reply = $socket->receive();
echo 'reply: ', $reply?->text() ?? '-', "\n";
$socket->close();
} catch (RuntimeError $refused) {
echo $refused->message, "\n";
}
Output
Core\Http\Client::openSocket cannot connect to 10.0.0.7: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["10.0.0.7"]` under `[capabilities.net]` in nvs.toml

What the url and options must be

<?nvs
// Shows the checks on the URL and on the options, which happen before anything
// is sent.
// A WebSocket URL starts with `ws://` or `wss://`. An `https://` URL throws an error.
try {
var $wrongScheme = Core\Http\Client::openSocket('https://203.0.113.10/live');
} catch (RuntimeError $scheme) {
echo $scheme->message, "\n";
}
// `idle` is how long the connection may stay quiet. It must be longer than zero.
try {
var $noWait = Core\Http\Client::openSocket('wss://203.0.113.10/live', { idle: 0s });
} catch (RuntimeError $idle) {
echo $idle->message, "\n";
}
// `maxDuration` is how long the connection may stay open. It must be longer than zero too.
try {
var $noTime = Core\Http\Client::openSocket('wss://203.0.113.10/live', { maxDuration: 0s });
} catch (RuntimeError $lifetime) {
echo $lifetime->message, "\n";
}
Output
Core\Http\Client::openSocket: the scheme must be `ws` or `wss`, and this URL names `https`
Core\Http\Client::openSocket: `idle` must be a positive duration, and this one is 0ns
Core\Http\Client::openSocket: `maxDuration` must be a positive duration, and this one is 0ns

A price feed with a fallback

<?nvs
// Shows a job that reads live prices from a feed. If the feed cannot be
// reached, the job uses the last prices it knows.
array<float> $prices = ['EUR' => 1.08, 'GBP' => 1.27];
string $source = 'last known prices';
uint $updates = 0;
try {
// `protocols` is the message format the job offers. `maxMessage` is the largest message in bytes.
// The connection closes after 30 seconds without a message, or after 2 minutes.
Core\Http\Socket $feed = Core\Http\Client::openSocket('wss://192.168.4.20/prices', {
protocols: ['json'],
idle: 30s,
maxDuration: 2m,
maxMessage: 65536,
});
$feed->send('subscribe EUR GBP');
// `receive` returns `null` when the feed closes the connection.
var $message = $feed->receive();
while ($message != null) {
echo 'update: ', $message->text() ?? '(binary)', "\n";
$updates = $updates + 1;
$message = $feed->receive();
}
$feed->close();
$source = 'live feed';
} catch (RuntimeError $error) {
echo 'feed not available: ', $error->message, "\n";
}
// 192.168.4.20 is a private address, so this prints the last known prices.
foreach ($prices as string $currency => float $rate) {
echo $currency, ': ', $rate, "\n";
}
echo 'source: ', $source, ', updates: ', $updates, "\n";
Output
feed not available: Core\Http\Client::openSocket cannot connect to 192.168.4.20: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["192.168.4.20"]` under `[capabilities.net]` in nvs.toml
EUR: 1.08
GBP: 1.27
source: last known prices, updates: 0