Core\Socket::current
Core\Socket::current(): Core\SocketReturns the WebSocket connection your script is running for.
When a request calls Core\Socket::upgrade, the server starts a new script for the connection. That script calls current() first, and then talks to the client with receive() and send() on the connection it got. There is one connection per script, and every call returns an object for that same connection.
Only a script started for a connection has one. In an ordinary request, a command line program or a spawn script child, current() throws a LogicError.
The examples below send a welcome message, show the error outside a connection, and hand the connection to a class that handles the chat.
Return value
Returns Core\Socket. The connection. Call receive and send on it to talk to the client. Each call returns a new object for the same connection, so compare what the client sends, not the objects.
Errors
LogicErrorThe script is not running for a connection. An ordinary request, aspawn scriptchild and a command line program all throw this.
Examples
Sending a welcome
<?nvs// Shows the first line of every connection script, and a welcome message for the client.
// The `.nvsp` file beside this example plays a client that sends nothing and closes.Core\Socket $conn = Core\Socket::current();
// Each `sent:` line in the output is a message the client received.// This prints `sent: welcome to the chat`.$conn->send('welcome to the chat');sent: welcome to the chatOutside a connection
<?nvs// Shows what `current()` does in a program that is not running for a connection.
// This example has no `.nvsp` file, so it runs as an ordinary command line program.// `current()` throws a `LogicError`, and this prints `no connection here`.try { Core\Socket $conn = Core\Socket::current(); echo "connected\n";} catch (LogicError $e) { echo "no connection here\n";}no connection hereA chat class
<?nvs// Shows a connection script that hands its connection to a class that runs the chat.
class Chat{ public static function run(Core\Socket $conn, string $room): void { $conn->send('you joined ' . $room); ?Core\Socket\Message $message = $conn->receive(); while ($message != null) { $conn->send($room . ': ' . ($message->text() ?? '')); $message = $conn->receive(); } }}
// The `.nvsp` file beside this example plays a client that sends one line and closes.// This prints `sent: you joined lobby` and then `sent: lobby: hi there`.Chat::run(Core\Socket::current(), 'lobby');sent: you joined lobbysent: lobby: hi there