Core\Socket::upgrade
Core\Socket::upgrade(
string $entry,
mixed $arguments = null,
mixed $limits = null,
?array<string> $grants = null,
?string $on = null,
): voidTurns a request into a WebSocket connection. A WebSocket connection stays open, so the client and the server can send each other messages at any time.
You name what the connection runs: the path of a file, or a static method written Chat::run. The connection starts when the request ends. It runs in its own isolate (a separate copy of the program that shares no memory with the request). arguments: copies values into it.
The other options are the ones spawn script takes. limits: sets lower limits, such as { memory: "8M" }. grants: lists the capabilities the connection may use, and it gets only the ones the request also has. on: can only be "here", so on: "worker" does not compile.
Only a request that asks for a WebSocket can be upgraded. Any other request throws a RuntimeError, and so does a second call in the same request.
The examples below open a connection that runs a file, show the error for a normal page request, and open a chat connection only for a signed-in user.
Parameters
$entrystringWhat the connection runs: the path of a file, the same asspawn scripttakes, or a static method writtenChat::run. An anonymous function is not allowed, because the connection shares no values with the request.$argumentsmixeddefault nullThe values the connection starts with. They are copied into the connection. For a method, each value goes to the parameter with the same name. Ataintedvalue is stilltaintedin the connection.$limitsmixeddefault nullLower limits for the connection, written asspawn scriptwrites them:{ memory: "8M", cpu_time: "2s" }. The keys arememory,cpu_time,wall_time,max_outputandmax_tasks. A limit higher than the server's own has no effect. The connection stops when it reaches one.$grants?array<string>default nullThe capabilities the connection may use, such as["fs.read"]. It gets only the names in this list that the request itself has. An empty list gives it none. Without this option, it gets what the request has.$on?stringdefault nullWhere the connection runs. Only"here"is allowed, because the connection runs on the core that accepted the client."worker"does not compile.
Return value
Returns void. Nothing. The call prepares the connection, and it starts when the request ends.
Errors
RuntimeErrorThe request is not a WebSocket request. The$entryfile is not granted byscript.spawnor does not compile. Or this request already calledupgrade.LogicErrorAn$argumentsvalue cannot be copied into the connection: a resource, asecret, or an array nested too deep. For a method,$argumentsis missing a parameter or has a name the method does not declare.
Examples
Opening an echo connection
<?nvs// Shows how a request turns into a WebSocket connection that runs another file.
// The path starts at the folder of this file.// The connection starts when this request ends. The request can still print first.Core\Socket::upgrade('sockets/echo.nvs');echo 'upgrading ', Core\Request::path(), "\n";
// The `.nvsp` file beside this example plays a client that sends two messages.// `echo.nvs` then prints `sent: you said hello` and `sent: you said bye`.upgrading /live/echosent: you said hellosent: you said byeclosed: 1000 closingA request that is not a websocket
<?nvs// Shows what happens when a normal page request calls `Core\Socket::upgrade`.
// A browser that opens this address as a page sends no `Upgrade: websocket` header.// So there is no connection to upgrade, and the call throws a `RuntimeError`.try { Core\Socket::upgrade('sockets/echo.nvs');} catch (RuntimeError $error) { // This prints `this address needs a WebSocket client`. echo "this address needs a WebSocket client\n";}this address needs a WebSocket clientA chat for signed in users
<?nvs// Shows a chat where each signed-in user gets a connection in a chat room.
class Chat{ // The connection runs this method. `arguments:` gives each parameter by its name. public static function run(string $user, string $room): void { Core\Socket $conn = Core\Socket::current(); $conn->send($user . ' joined ' . $room); ?Core\Socket\Message $message = $conn->receive(); while ($message != null) { $conn->send($user . ': ' . ($message->text() ?? '')); $message = $conn->receive(); } }}
// This array gives the user for each session identifier in the `session` cookie.array<string> $users = ['c81f02' => 'Ana', '5be9d4' => 'Ben'];tainted string $session = Core\Request::cookie('session') ?? '';string $user = $users[$session] ?? '';
// Only a signed-in user gets a connection. Everybody else gets an error page.if ($user == '') { echo "401: sign in first\n";} else { Core\Socket::upgrade(Chat::run, arguments: ['user' => $user, 'room' => 'support']);}
// The client sends two messages. This prints `sent: Ana joined support`,// then `sent: Ana: hi` and `sent: Ana: is anyone here?`.sent: Ana joined supportsent: Ana: hisent: Ana: is anyone here?closed: 1000 closing