Core\Http\Client::openSocket
Core\Http\Client::openSocket(
string|Core\Http\Target $url,
{…},
): Core\Http\SocketOpens 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 awsorwssURL that the program wrote, or aCore\Http\TargetfromCore\Http::allowUrl. AnhttporhttpsURL is not allowed here. AtaintedURL comes from outside the program, such as from a request. Check it withCore\Http::allowUrlfirst.
Options
deadlineCore\Time\DurationoptionalThe time limit for the opening handshake. It covers the connection and every address tried, and it ends when the101reply arrives. After that,idleandmaxDurationlimit the conversation. If it is not given, the runtime's[http.client] deadlineis 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 ofdeadline, and is not added to it.headersarray<secret string>optionalExtra request headers, by name. Asecretvalue 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. Ataintedvalue 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 withCore\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] rootscertificates. The URL's host must be in theanchorsgrant ofcapabilities.tls. If it is not, the call throws an error before it connects.tlsPinstring|array<string>optionalOnesha256//<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 thepingrant.tlsVerifyHostbooloptionalIf it isfalse, the chain is still checked, and only the name check is skipped. The host must be in theany_namegrant.tlsVerifybooloptionalIf it isfalse, 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 theinsecuregrant.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_versionthrows 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 thenet.connect_togrant. The deployment's address policy checks this address like a looked-up one. With aCore\Http\Targetas the URL, this option throws an error, because the target already has its approved addresses.protocolsarray<string>optionalThe subprotocols to offer inSec-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::protocolreturns 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] idleis used. There is no way to turn this limit off. Withpingset, 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 theidlecheck. If it is not given, the runtime's[http.client] max_durationis used.maxMessageuintoptionalThe largest message, in bytes, that this side builds from the server's fragments. A larger message closes the socket with code1009. The waitingreceivethen throws an error that names the limit. If it is not given, the runtime's[http.client.socket] max_messageis used.sendTimeoutCore\Time\DurationoptionalThe longest time a frame may wait to be sent to a server that is not reading. It is also how longclosewaits for the server's own close frame. If it is not given, the runtime's[http.client.socket] send_timeoutis used.pingCore\Time\DurationoptionalHow long the socket stays silent before it sends a ping. A live server answers the ping, soidlecloses 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 notwsorwss, or it has no host. This method does not accepthttporhttps, and the other methods do not acceptwsorwss. Ornet.connectdoes not grant the host, or the host resolves to an address the deployment's policy denies. An option is out of range. Adeadline,connectTimeout,idle,maxDuration,sendTimeoutorpingis not a positive duration. Or aprotocolsentry is not one word. Or the server did not open a socket. It sent a redirect, which is never followed, and the message names itsLocation. Or it sent a status other than101. Or it chose a subprotocol thatprotocolsdid not offer.
Examples
The examples below run with this configuration file.
# 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";}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 excepthelp: add `internal = ["10.0.0.7"]` under `[capabilities.net]` in nvs.tomlWhat 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";}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 0nsCore\Http\Client::openSocket: `maxDuration` must be a positive duration, and this one is 0nsA 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";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 excepthelp: add `internal = ["192.168.4.20"]` under `[capabilities.net]` in nvs.tomlEUR: 1.08GBP: 1.27source: last known prices, updates: 0