add doc/*/scripting/builtins/libnetwork.md

This commit is contained in:
MihailRis 2024-11-28 18:09:12 +03:00
parent ca83dcf9a7
commit 95689b1115
5 changed files with 191 additions and 0 deletions

View File

@ -22,6 +22,7 @@ Subsections:
- [inventory](scripting/builtins/libinventory.md)
- [item](scripting/builtins/libitem.md)
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)

View File

@ -0,0 +1,94 @@
# *network* library
A library for working with the network.
## HTTP requests
```lua
-- Performs a GET request to the specified URL.
-- After receiving the response, passes the text to the callback function.
network.get(url: str, callback: function(str))
-- Example:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
print(json.parse(s).name) -- will output the name of the latest engine release
end)
-- A variant for binary files, with a byte array instead of a string in the response.
network.get_binary(url: str, callback: function(table|ByteArray))
```
## TCP Connections
```lua
network.tcp_connect(
-- Address
address: str,
-- Port
port: int,
-- Function called upon successful connection
-- Sending will not work before connection
-- Socket is passed as the only argument
callback: function(Socket)
) --> Socket
```
Initiates TCP connection.
The Socket class has the following methods:
```lua
-- Sends a byte array
socket:send(table|ByteArray)
-- Reads the received data
socket:recv(
-- Maximum size of the byte array to read
length: int,
-- Use table instead of Bytearray
[optional] usetable: bool=false
) -> nil|table|Bytearray
-- Returns nil on error (socket is closed or does not exist).
-- If there is no data yet, returns an empty byte array.
-- Closes the connection
socket:close()
-- Checks that the socket exists and is not closed.
socket:is_alive() --> bool
-- Checks if the connection is present (using socket:send(...) is available).
socket:is_connected() --> bool
```
```lua
-- Opens a TCP server.
network.tcp_open(
-- Port
port: int,
-- Function called when connecting
-- The socket of the connected client is passed as the only argument
callback: function(Socket)
) --> ServerSocket
```
The SocketServer class has the following methods:
```lua
-- Closes the server, breaking connections with clients.
server:close()
-- Checks if the TCP server exists and is open.
server:is_open() --> bool
```
## Analytics
```lua
-- Returns the approximate amount of data sent (including connections to localhost)
-- in bytes.
network.get_total_upload() --> int
-- Returns the approximate amount of data received (including connections to localhost)
-- in bytes.
network.get_total_download() --> int
```

View File

@ -22,6 +22,7 @@
- [inventory](scripting/builtins/libinventory.md)
- [item](scripting/builtins/libitem.md)
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)

View File

@ -0,0 +1,94 @@
# Библиотека *network*
Библиотека для работы с сетью.
## HTTP-запросы
```lua
-- Выполняет GET запрос к указанному URL.
-- После получения ответа, передаёт текст в функцию callback.
network.get(url: str, callback: function(str))
-- Пример:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
print(json.parse(s).name) -- выведет имя последнего релиза движка
end)
-- Вариант для двоичных файлов, с массивом байт вместо строки в ответе.
network.get_binary(url: str, callback: function(table|ByteArray))
```
## TCP-Соединения
```lua
network.tcp_connect(
-- Адрес
address: str,
-- Порт
port: int,
-- Функция, вызываемая при успешном подключении
-- До подключения отправка работать не будет
-- Как единственный аргумент передаётся сокет
callback: function(Socket)
) --> Socket
```
Инициирует TCP подключение.
Класс Socket имеет следующие методы:
```lua
-- Отправляет массив байт
socket:send(table|ByteArray)
-- Читает полученные данные
socket:recv(
-- Максимальный размер читаемого массива байт
length: int,
-- Использовать таблицу вместо Bytearray
[опционально] usetable: bool=false
) -> nil|table|Bytearray
-- В случае ошибки возвращает nil (сокет закрыт или несуществует).
-- Если данных пока нет, возвращает пустой массив байт.
-- Закрывает соединение
socket:close()
-- Проверяет, что сокет существует и не закрыт.
socket:is_alive() --> bool
-- Проверяет наличие соединения (доступно использование socket:send(...)).
socket:is_connected() --> bool
```
```lua
-- Открывает TCP-сервер.
network.tcp_open(
-- Порт
port: int,
-- Функция, вызываемая при поключениях
-- Как единственный аргумент передаётся сокет подключенного клиента
callback: function(Socket)
) --> ServerSocket
```
Класс SocketServer имеет следующие методы:
```lua
-- Закрывает сервер, разрывая соединения с клиентами.
server:close()
-- Проверяет, существует и открыт ли TCP сервер.
server:is_open() --> bool
```
## Аналитика
```lua
-- Возвращает приблизительный объем отправленных данных (включая соединения с localhost)
-- в байтах.
network.get_total_upload() --> int
-- Возвращает приблизительный объем полученных данных (включая соединения с localhost)
-- в байтах.
network.get_total_download() --> int
```

View File

@ -99,6 +99,7 @@ public:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, request.followLocation);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl");
if (request.maxSize == 0) {
curl_easy_setopt(
curl, CURLOPT_MAXFILESIZE, std::numeric_limits<long>::max()