Networking
This section contains the references for communicating over networks and the internet.
Which part to use depends on what is being talked to:
- For multiplayer games, where NVGT programs talk to each other, the network class handles connections, peers, channels and reliable or unreliable messages.
- For web requests, such as checking for updates, downloading files or using a web API, the http class is the best choice for almost everything. It makes HTTP and HTTPS requests in the background, follows redirects and handles authentication, and url_get() and url_post() make simple requests in one line.
- For full control over HTTP, http_client and https_client send http_request objects and receive http_response objects over a connection that the script manages.
- For services that use WebSockets, such as many chat and real time web services, see web_socket.
- For other protocols over TCP, stream_socket sends and receives raw bytes.
- For sending email, see smtp_client and mail_message.
spec::uri, spec::ip_address, socket_address and the DNS functions describe and look up addresses for all of these.
classes
dns_host_entry
The result of looking up a host with DNS, its canonical name, aliases and addresses.
dns_host_entry();
dns_host_entry(const dns_host_entry&in other);
Arguments:
- const dns_host_entry&in other (2): an entry to copy.
Remarks:
These are returned by dns_resolve() and system_dns_host_entry().
Example:
void main() {
dns_host_entry entry = dns_resolve("nvgt.dev");
string info = "name: " + entry.name;
spec::ip_address[]@ addresses = entry.get_addresses();
for (uint i = 0; i < addresses.length(); i++) info += "\naddress: " + addresses[i];
string[]@ aliases = entry.get_aliases();
for (uint i = 0; i < aliases.length(); i++) info += "\nalias: " + aliases[i];
alert("DNS", info);
}
Methods
get_addresses
Get the IP addresses of the host.
array<spec::ip_address>@ dns_host_entry::get_addresses() const;
Returns:
arrayspec::ip_address@: the addresses the host resolved to, IPv4 and IPv6.
get_aliases
Get the other names of the host.
array<string>@ dns_host_entry::get_aliases() const;
Returns:
array
Properties
name
The canonical name of the host.
const string dns_host_entry::name;
ftp_client
Connect to an FTP server to browse its directories and to download, upload and manage files.
ftp_client(uint16 active_data_port = 0);
ftp_client(const string&in host, uint16 port = 21, const string&in username = "", const string&in password = "", uint16 active_data_port = 0);
Arguments (1):
- uint16 active_data_port = 0: the local port that the server connects to for transfers when passive mode is turned off, where 0 lets the system choose a free one.
Arguments (2):
const string&in host: the name or address of the server.
uint16 port = 21: the port of the server.
const string&in username = "": the user to log in as, which should be "anonymous" for servers that allow anyone to download. If it is empty, no login is attempted and login() must be called before most commands.
const string&in password = "": the password to log in with, which for anonymous access is conventionally an email address.
uint16 active_data_port = 0: as above.
Remarks:
The first constructor creates a client that isn't connected yet, which is connected with open(). The second one connects immediately and logs in if a username is given.
Every method blocks until the server responds and throws an exception if something goes wrong, such as a connection that is refused, a login that is rejected or a file that doesn't exist, and the exception contains the message of the server or the network error. Socket operations time out after 30 seconds, which can't be changed.
File transfers use a second connection to the server. By default it is made in passive mode, where the client connects to the server, which works through firewalls and routers. Call set_passive(false) for servers that need active mode, in which the server connects to the client. Transfers are done with the begin_ methods, which return a datastream that is read from or written to, and the matching end_ method must be called afterwards, before another command is sent. Only one transfer can be in progress at a time.
The connection is not encrypted, so passwords and files are sent as plain text, and is_secure is therefore always false.
Example:
void main() {
ftp_client ftp;
try {
ftp.open("ftp.gnu.org", 21, "anonymous", "guest@example.com");
alert("Connected", ftp.welcome_message);
ftp.set_working_directory("gnu");
datastream@ listing = ftp.begin_list();
string names = listing.read();
ftp.end_list();
alert("Contents of " + ftp.get_working_directory(), names);
ftp.close();
} catch {
alert("Error", get_exception_info());
}
}
Methods
abort
Cancel the download or upload that is in progress.
void ftp_client::abort();
Remarks:
It is not necessary to call end_download() or end_upload() after this.
begin_download
Start downloading a file from the server.
datastream@ ftp_client::begin_download(const string&in path, const string&in encoding = "", int byteorder = STREAM_BYTE_ORDER_NATIVE);
Arguments:
- const string&in path: the file to download.
- const string&in encoding = "": the text encoding of the returned datastream, see datastream.
- int byteorder = STREAM_BYTE_ORDER_NATIVE: the byte order of the returned datastream.
Returns:
datastream@: a stream that the contents of the file are read from.
Remarks:
Read the whole file from the stream, for example with read(), and then call end_download(). The stream is only valid until then and can't be closed by the script. An exception is thrown if the file doesn't exist or the data connection can't be made.
begin_list
Start downloading a listing of a directory.
datastream@ ftp_client::begin_list(const string&in path = "", bool extended = false, const string&in encoding = "", int byteorder = STREAM_BYTE_ORDER_NATIVE);
Arguments:
- const string&in path = "": the directory to list, or a file to get information about only that file. An empty path lists the current working directory.
- bool extended = false: false to get only the names, one per line, or true to get a full listing with sizes, dates and permissions.
- const string&in encoding = "": the text encoding of the returned datastream, see datastream.
- int byteorder = STREAM_BYTE_ORDER_NATIVE: the byte order of the returned datastream.
Returns:
datastream@: a stream that the text of the listing is read from.
Remarks:
Read all of the listing from the stream, and then call end_list(). The stream is only valid until then. The format of an extended listing depends on the server and isn't interpreted, so use the names only listing when the result needs to be processed by the game.
begin_upload
Start uploading a file to the server.
datastream@ ftp_client::begin_upload(const string&in path, const string&in encoding = "", int byteorder = STREAM_BYTE_ORDER_NATIVE);
Arguments:
- const string&in path: the path of the file to create on the server.
- const string&in encoding = "": the text encoding of the returned datastream, see datastream.
- int byteorder = STREAM_BYTE_ORDER_NATIVE: the byte order of the returned datastream.
Returns:
datastream@: a stream that the contents of the file are written to.
Remarks:
Write the whole file to the stream, and then call end_upload(). The stream is only valid until then and can't be closed by the script. An exception is thrown if the file can't be created or the data connection can't be made.
cdup
Go up one directory on the server.
void ftp_client::cdup();
close
Tell the server goodbye and close the connection.
void ftp_client::close();
Remarks:
After this, is_open is false and open() can be used to connect again.
create_directory
Create a directory on the server.
void ftp_client::create_directory(const string&in path);
Arguments:
- const string&in path: the directory to create.
end_download
Finish a download started with begin_download().
void ftp_client::end_download();
Remarks:
Call this once all data has been read, before sending any other command. Use abort() to cancel a download that you don't want to finish.
end_list
Finish a listing started with begin_list().
void ftp_client::end_list();
Remarks:
Call this once all of the listing has been read, before sending any other command.
end_upload
Finish an upload started with begin_upload().
void ftp_client::end_upload();
Remarks:
Call this once all data has been written, before sending any other command. The upload isn't complete until this is called.
get_working_directory
Get the current directory on the server.
string ftp_client::get_working_directory();
Returns:
string: the path of the directory the client is in, which is usually the home directory of the user right after logging in.
login
Log in to the server.
void ftp_client::login(const string&in username, const string&in password);
Arguments:
- const string&in username: the user to log in as.
- const string&in password: the password to log in with.
Remarks:
This has to be called after open() if no username was given to it, before any other commands except close(). An exception is thrown if the server rejects the login.
logout
Log out from the server without closing the connection.
void ftp_client::logout();
Remarks:
Any transfer that is in progress is ended. Use close() instead when you are done with the server.
open
Connect to an FTP server, and log in if a username is given.
void ftp_client::open(const string&in host, uint16 port, const string&in username = "", const string&in password = "");
Arguments:
- const string&in host: the name or address of the server.
- uint16 port: the port of the server, which is 21 for most servers.
- const string&in username = "": the user to log in as, such as "anonymous". If it is empty, call login() afterwards.
- const string&in password = "": the password to log in with.
Remarks:
An exception is thrown if the connection can't be made or the login is rejected. The welcome message of the server is available in welcome_message once connected.
remove
Delete a file on the server.
void ftp_client::remove(const string&in path);
Arguments:
- const string&in path: the file to delete.
Remarks:
Use remove_directory() to delete a directory.
remove_directory
Delete a directory on the server.
void ftp_client::remove_directory(const string&in path);
Arguments:
- const string&in path: the directory to delete.
Remarks:
Servers usually only delete directories that are empty.
rename
Rename or move a file or directory on the server.
void ftp_client::rename(const string&in source, const string&in destination);
Arguments:
- const string&in source: the current path.
- const string&in destination: the new path.
send_command
Send a command to the server exactly as it is given and wait for the response.
int ftp_client::send_command(const string&in command, string& response);int ftp_client::send_command(const string&in command, const string&in argument, string& response);
Arguments:
- const string&in command: the FTP command, such as
NOOP. - const string&in argument (2): the argument of the command.
- string& response: receives the text of the response of the server.
Returns:
int: the status code of the response, such as 200 for success.
Remarks:
This is for commands that the other methods don't cover.
set_file_type
Choose how files are transferred.
void ftp_client::set_file_type(ftp_file_type type);
Arguments:
- ftp_file_type type: FTP_FILE_TYPE_BINARY, which is the default, or FTP_FILE_TYPE_TEXT.
Remarks:
Binary mode transfers files exactly as they are. In text mode, the receiving side is expected to convert line endings itself, and this client does no conversion, so binary is almost always correct. The current type is available in the file_type property.
set_passive
Choose between passive and active mode for file transfers.
void ftp_client::set_passive(bool passive, bool use_rfc1738 = true);
Arguments:
- bool passive: true for passive mode, in which the client connects to the server for transfers, or false for active mode, in which the server connects to the client.
- bool use_rfc1738 = true: whether to try the newer EPSV and EPRT commands, which also work with IPv6 and NAT, before falling back to the older PASV and PORT commands.
Remarks:
Passive mode is the default and is the one that works from behind routers and firewalls. Active mode needs the server to be able to reach the computer that is running your game, and can use the port given to the constructor. The current mode is available in the passive property.
set_working_directory
Change the current directory on the server.
void ftp_client::set_working_directory(const string&in path);
Arguments:
- const string&in path: the directory to go to, either absolute or relative to the current one.
Remarks:
An exception is thrown if the directory doesn't exist or can't be entered.
system_type
Ask the server what kind of system it runs on.
string ftp_client::system_type();
Returns:
string: the answer of the server to the SYST command, such as UNIX Type: L8.
Properties
file_type
How files are transferred.
const ftp_file_type ftp_client::file_type;
Remarks:
This is FTP_FILE_TYPE_BINARY by default. Change it with set_file_type().
is_logged_in
Whether the client has logged in to the server.
const bool ftp_client::is_logged_in;
is_open
Whether the connection to the server is open.
const bool ftp_client::is_open;
is_secure
Whether the connection is encrypted.
const bool ftp_client::is_secure;
Remarks:
This is always false, as only plain FTP is supported.
passive
Whether file transfers use passive mode.
const bool ftp_client::passive;
Remarks:
This is true by default. Change it with set_passive().
welcome_message
The greeting that the server sent when the connection was made.
const string ftp_client::welcome_message;
Remarks:
This is empty until the client has connected.
http
Make HTTP and HTTPS requests in the background through a simple interface.
http();
Remarks:
This is the easiest way to make a web request in NVGT, and the best choice for almost every HTTP operation, from checking for updates to downloading files and talking to web APIs. Create an http object, start a request with a method such as get() or post(), and then either wait() for it or keep running the game while checking properties such as progress, status_code and response_body.
Requests run on a thread of their own, so the game never stops while one is in progress. Redirects are followed automatically, and if the server asks for authentication, the credentials given to the request or found in the URL's user info are sent.
The response body is collected as it downloads, and reading response_body returns what has arrived since it was last read, so a large download can be written to a file a piece at a time. Destroying the http object or calling reset() cancels the request.
For a one line blocking request, see url_get() and url_post(), which use this class. For complete control over the requests and the connection, see http_client, http_request and http_response.
Example:
#include "size.nvgt"
#include "speech.nvgt"
void main() {
// This script downloads the latest NVGT windows installer and saves it in the current working directory.
http h;
h.get("https://nvgt.zip/windows");
file f;
string filename = "";
show_window("downloading...");
while (!h.complete) {
wait(5);
if (key_pressed(KEY_ESCAPE)) {
f.close();
file_delete(filename);
return; // Destruction of the http object will cancel any requests in progress.
}
if (!f.active and h.status_code == 200) { // The file is available.
string[]@ path = h.url.get_path_segments();
filename = path.length() > 0? path[-1] : "http.txt";
f.open(filename, "wb");
}
if (f.active) f.write(h.response_body);
if (key_pressed(KEY_SPACE)) speak(round(h.progress * 100, 2) + "%");
}
int keep = question(filename, size_to_string(f.size) + " downloaded, keep file?");
f.close();
if (keep != 1) file_delete(filename);
}
Methods
connect
Start an HTTP CONNECT request in the background. This asks a proxy server to open a tunnel to the URL's host.
bool http::connect(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
delete
Start an HTTP DELETE request in the background. This asks the server to delete what is at the URL.
bool http::delete(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
get
Start an HTTP GET request in the background. This downloads whatever the URL points to, such as a web page, a file or the result of an API call.
bool http::get(const spec::uri&in url, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}.const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
Example:
void main() {
// Fetch the latest version of NVGT.
http h;
if (!h.get("http://nvgt.dev/downloads/latest_version")) {
alert("oops", "request failed");
return;
}
h.wait(); // You can also use the h.running or h.complete properties in a loop to execute code in the background while the request progresses.
alert("nvgt latest version", h.response_body);
}
head
Start an HTTP HEAD request in the background. This is like get(), but the server only sends the response headers, which is useful for finding out the size or type of a file without downloading it.
bool http::head(const spec::uri&in url, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
options
Start an HTTP OPTIONS request in the background. This asks the server which methods and features the URL supports.
bool http::options(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
patch
Start an HTTP PATCH request in the background. This sends a body describing changes to make to what is at the URL.
bool http::patch(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
post
Start an HTTP POST request in the background. This sends a body to the server, usually to submit a form or send data to an API.
bool http::post(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
const string&in body: the body of the request, such as form data or JSON.
const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}.const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
Example:
void main() {
http h;
name_value_collection headers = \{\{"Content-Type", "application/json"\}\};
h.post("https://httpbin.org/post", "{\"player\": \"Sam\", \"score\": 1500}", headers);
h.wait();
alert("Status " + h.status_code, h.response_body);
}
put
Start an HTTP PUT request in the background. This sends a body which the server should store at the URL, replacing anything there.
bool http::put(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
request
Get the part of the response body that has arrived since it was last read.
string http::request();
Returns:
string: the newly arrived data, which is removed from the http object.
Remarks:
This is the same as reading response_body.
reset
Cancel the current request, if any, and clear the response.
void http::reset(bool configuration = false);
Arguments:
- bool configuration = false: whether to also restore the settings, max_retries, retry_delay, keepalive and the timeouts, to their defaults.
Remarks:
This waits for the current request to cancel, which is usually instant, though there can be a short delay while the request's thread reaches a point where it checks for cancellation.
Starting a new request resets the previous one automatically, and destroying the http object resets it too, so this is only needed to cancel a request or free the memory of its response.
Example:
void main() {
http h;
h.get("https://nvgt.dev");
wait(20);
h.reset();
h.get("https://samtupy.com/ip.php");
h.wait();
if (h.status_code != 200) alert("oops " + h.status_code, h.response_body);
else alert("IP address displayed after http reset", h.response_body);
}
trace
Start an HTTP TRACE request in the background. This asks the server to send the request back as it received it, which is mostly useful for debugging.
bool http::trace(const spec::uri&in url, const string&in body, const name_value_collection@ headers = null, const http_credentials@ creds = null);
Arguments:
- const spec::uri&in url: the URL to request, which must have a scheme of http or https. A string can be passed directly.
- const string&in body: the body of the request, such as form data or JSON.
- const name_value_collection@ headers = null: extra headers to send with the request, such as
\{\{"Accept", "application/json"\}\}. - const http_credentials@ creds = null: credentials to authenticate with if the server asks for them.
Returns:
bool: true if the request was started, false if the URL's scheme isn't http or https or a request is already running.
Remarks:
Any previous request made with this object is reset first. While the request runs, its status_code, response_headers, progress and response_body can be checked, and complete becomes true when it has finished, whether or not it succeeded.
wait
Wait for the current request to finish.
void http::wait();
Remarks:
This blocks the script until the request completes, which is simple but stops the game from doing anything else meanwhile. To keep the game running, check the complete property in the game loop instead.
Properties
complete
Whether the request has finished, successfully or not.
const bool http::complete;
Remarks:
This is also true when no request has been made.
connect_timeout
How many milliseconds to wait for a connection to the server before giving up.
uint http::connect_timeout;
Remarks:
This defaults to 30000, 30 seconds.
keepalive
Whether the connection is kept open in case more requests are made to the same server.
bool http::keepalive;
Remarks:
This defaults to false.
keepalive_timeout
How many milliseconds an idle connection is kept open when keepalive is enabled.
uint http::keepalive_timeout;
Remarks:
This defaults to 10000, 10 seconds.
max_retries
The maximum number of times a request is sent, counting the requests made to follow redirects, to retry with credentials and to try again after a network error.
uint http::max_retries;
Remarks:
This defaults to 10. When the connection fails or is interrupted, the request is sent again after retry_delay milliseconds, discarding any part of the response body that had already arrived, until it succeeds or the tries run out. A value of 1 means the request is never repeated, though it also means that redirects are not followed. Every redirect and authentication attempt uses up one try as well. It is kept between requests, and only restored to the default by reset(true).
progress
How much of the response has been downloaded, from 0.0 to 1.0.
const float http::progress;
Remarks:
This is 0 until the response headers arrive, and -1 if the progress can't be known, such as when the server doesn't send a Content-Length header.
receive_timeout
How many milliseconds receiving from the server may block before the request fails.
uint http::receive_timeout;
Remarks:
This defaults to 60000, a minute.
response_body
The part of the response body that has arrived since this property was last read.
const string http::response_body;
Remarks:
Reading this property removes what it returns from the http object, so that a download can be processed or written to a file as it arrives without keeping all of it in memory. For example, h.response_body.length() throws the data away, and the next read returns only what arrived after it. Either append this property to a string or stream in a loop while the request runs, or read it once after the request completes to get the whole body.
The request() method does the same.
response_headers
The headers of the response, along with its status and reason.
const http_response@ http::response_headers;
Remarks:
This is a copy of the response as it is when read, so it should be read again after the request completes. Before the response arrives, it is empty. A single header can also be read by indexing the http object, such as h["Content-Type"].
retry_delay
How many milliseconds to wait before sending each request, including the first and every retry after a network error.
uint http::retry_delay;
Remarks:
This defaults to 0. It is kept between requests, and only restored to the default by reset(true).
running
Whether a request is in progress.
const bool http::running;
send_timeout
How many milliseconds sending to the server may block before the request fails.
uint http::send_timeout;
Remarks:
This defaults to 60000, a minute.
status_code
The HTTP status code of the response, such as 200 for success or 404 if nothing was found.
const int http::status_code;
Remarks:
This is 0 until the response headers arrive, and stays 0 if the request failed without a response, such as when the host can't be reached. See the http_status enum for the codes, and http_status_reason() to describe one.
url
The URL of the current request.
const spec::uri http::url;
Remarks:
When a redirect is followed, this changes to the URL that was redirected to.
user_agent
The User-Agent header sent with requests, which identifies the program making them.
string http::user_agent;
Remarks:
This defaults to nvgt followed by NVGT's version. Setting it to an empty string restores the default. It applies to requests started after it is set.
uuid
A unique identifier for this http object, generated when it is created.
const uuid http::uuid;
Remarks:
This can be used to tell many http objects apart, such as when keeping them in a dictionary.
http_client
A connection to an HTTP server, which sends http_request objects and receives http_response objects.
http_client(const string&in host, uint16 port = 80);
Arguments:
const string&in host: the host to connect to, such as
nvgt.dev.uint16 port = 80: the port to connect to.
Remarks:
For most HTTP requests, the http class is far easier to use, as it runs the request in the background, follows redirects, handles authentication and works with both http and https URLs. This lower level class is for when more control over the request and the connection is needed.
The client connects when the first request is sent, and with keep_alive can send further requests over the same connection. Every method blocks until it is done, and an exception is thrown if connecting, sending or receiving fails.
http_client only speaks plain HTTP. For HTTPS use https_client, which has the same methods and converts to an http_client implicitly, so code can be written for both.
Example:
void main() {
http_client client("httpbin.org");
http_request req(HTTP_GET, "/get");
client.send_request(req);
http_response resp;
datastream@ body = client.receive_response(resp);
alert("Status " + resp.status, body.read());
}
Methods
abort
Close the connection straight away, abandoning any request in progress.
void http_client::abort();
flush_request
Make sure everything written to the request's stream has been sent to the server.
void http_client::flush_request();
Remarks:
receive_response() does this itself.
peek_response
Receive the response to a request sent with expect_continue, before sending its body.
bool http_client::peek_response(http_response&inout response);
Arguments:
- http_response&inout response: receives the status and headers of the response.
Returns:
bool: true if the server responded with 100 Continue, in which case the body should be sent and receive_response() called, or false if it sent a final response, which response then holds.
receive_response
Receive the response to the request that was sent.
datastream@ http_client::receive_response(http_response&inout response, const string&in encoding = "", int byteorder = STREAM_BYTE_ORDER_NATIVE);
Arguments:
- http_response&inout response: receives the status and headers of the response.
- const string&in encoding = "": the text encoding of the returned stream.
- int byteorder = STREAM_BYTE_ORDER_NATIVE: the byte order of the returned stream.
Returns:
datastream@: a stream to read the body of the response from.
Remarks:
The stream belongs to the client and is only valid until the next request. An exception is thrown if receiving fails or times out.
reset
Close the connection, so that the next request opens a new one.
void http_client::reset();
send_request
Send a request to the server, connecting first if needed.
datastream@ http_client::send_request(http_request&inout request, const string&in encoding = "", int byteorder = STREAM_BYTE_ORDER_NATIVE);
Arguments:
- http_request&inout request: the request to send. Its Host header is set from the client if it has none.
- const string&in encoding = "": the text encoding of the returned stream.
- int byteorder = STREAM_BYTE_ORDER_NATIVE: the byte order of the returned stream.
Returns:
datastream@: a stream to write the body of the request to, if it has one.
Remarks:
After writing the body, if any, call receive_response(). An exception is thrown if the connection fails.
Properties
connected
Whether the client is connected to the server.
const bool http_client::connected;
host
The host the client connects to.
string http_client::host;
Remarks:
This can only be changed while the client isn't connected.
keep_alive
Whether the connection is kept open after a request so the next one can reuse it.
bool http_client::keep_alive;
Remarks:
This defaults to false, and is set on each request sent, unless the request sets its own keep_alive.
keep_alive_timeout
How long an idle kept alive connection is reused before a new one is made.
timespan http_client::keep_alive_timeout;
Remarks:
This defaults to 8 seconds.
port
The port the client connects to.
uint16 http_client::port;
Remarks:
This can only be changed while the client isn't connected.
receive_timeout
How long receiving may block before an exception is thrown.
timespan http_client::receive_timeout;
Remarks:
This defaults to 60 seconds.
secure
Whether the client uses TLS, which is true for https_client.
const bool http_client::secure;
send_timeout
How long sending may block before an exception is thrown.
timespan http_client::send_timeout;
Remarks:
This defaults to 60 seconds.
http_credentials
A username and password for HTTP authentication, which can answer a server's request for authentication with Basic, Digest or NTLM credentials.
http_credentials();
http_credentials(const string&in username, const string&in password);
Arguments:
const string&in username (2): the username to authenticate with.
const string&in password (2): the password to authenticate with.
Remarks:
The http class handles authentication itself when given an http_credentials object, so this class is mainly for use with http_client. When a server responds with HTTP_UNAUTHORIZED, pass the request and that response to authenticate(), which adds the right Authorization header for whichever scheme the server asked for, and send the request again.
Example:
void main() {
http_credentials creds("user", "passwd");
http h;
h.get("https://httpbin.org/basic-auth/user/passwd", null, creds);
h.wait();
alert("Status " + h.status_code, h.response_body);
}
Methods
authenticate
Add an Authorization header to a request in answer to a server's response asking for authentication.
void http_credentials::authenticate(http_request&inout request, const http_response&in response);
Arguments:
- http_request&inout request: the request to add the header to, which should then be sent again.
- const http_response&in response: the HTTP_UNAUTHORIZED response, whose WWW-Authenticate header says which scheme to use.
Remarks:
An exception is thrown if the server asks for a scheme that isn't supported.
clear
Clear the username, password and host.
void http_credentials::clear();
from_uri
Set the username and password from the user info of a URI, such as https://user:password@example.com/.
void http_credentials::from_uri(const spec::uri&in uri);
Arguments:
- const spec::uri&in uri: the URI to take the user info from.
from_user_info
Set the username and password from the user info part of a URL, such as user:password.
void http_credentials::from_user_info(const string&in user_info);
Arguments:
- const string&in user_info: the user info to parse.
proxy_authenticate
Add a Proxy-Authorization header to a request in answer to a proxy's response asking for authentication.
void http_credentials::proxy_authenticate(http_request&inout request, const http_response&in response);
Arguments:
- http_request&inout request: the request to add the header to.
- const http_response&in response: the HTTP_PROXY_AUTHENTICATION_REQUIRED response.
update_auth_info
Update the Authorization header of a request that was already authenticated, before sending it again.
void http_credentials::update_auth_info(http_request&inout request);
Arguments:
- http_request&inout request: the request to update.
Remarks:
Digest authentication requires this for each new request, as it includes a count of the requests made.
update_proxy_auth_info
Update the Proxy-Authorization header of a request that was already authenticated with a proxy.
void http_credentials::update_proxy_auth_info(http_request&inout request);
Arguments:
- http_request&inout request: the request to update.
Properties
empty
Whether no username has been set.
const bool http_credentials::empty;
host
The host the credentials are for, which is needed by NTLM authentication.
string http_credentials::host;
password
The password to authenticate with.
string http_credentials::password;
username
The username to authenticate with.
string http_credentials::username;
http_request
An HTTP request, with its method, URI, version and headers, for sending with http_client.
http_request();
http_request(const http_request&in other);
http_request(const string&in method, const string&in uri, const string&in version = HTTP_1_1);
http_request(\{\{string, string}, ...});
Arguments:
const http_request&in other (2): a request to copy.
const string&in method (3): the method of the request, such as HTTP_GET or HTTP_POST.
const string&in uri (3): what to request from the server, usually the path and query of a URL, such as
/docs/?search=sound.const string&in version = HTTP_1_1 (3): the HTTP version of the request.
\{\{string, string}, ...} (4): the names and values of the request's headers, each pair in its own set of braces.
Remarks:
For most HTTP requests, the http class is far easier to use, as it runs the request in the background, follows redirects, handles authentication and works with both http and https URLs. This lower level class is for when more control over the request and the connection is needed.
An http_request is an internet_message_header holding the request's headers, so headers are set by indexing it, as in req["Accept"] = "text/html";, and it has every method of internet_message_header and name_value_collection as well as the ones listed here. It can be created from an initialization list of headers.
The request doesn't include its body, which is written to the stream returned by http_client::send_request() after the content_length or chunked_transfer_encoding is set.
Example:
void main() {
http_request req(HTTP_GET, "/downloads/latest_version", HTTP_1_1);
req.host = "nvgt.dev";
req["Accept"] = "text/plain";
req.set_credentials("Bearer", "my_token");
string info = req.method + " " + req.uri + " " + req.version + "\nhost: " + req.host;
for (uint i = 0; i < req.size(); i++) info += "\n" + req.name_at(i) + ": " + req.value_at(i);
alert("Request", info);
}
Methods
get_cookies
Get the cookies sent in the request's Cookie header.
void http_request::get_cookies(name_value_collection&inout cookies) const;
Arguments:
- name_value_collection&inout cookies: the collection the cookies are added to.
get_credentials
Get the authentication scheme and information of the request's Authorization header.
void http_request::get_credentials(string&inout scheme, string&inout auth_info) const;
Arguments:
- string&inout scheme: receives the scheme, such as
BasicorBearer. - string&inout auth_info: receives the information following the scheme, such as an encoded username and password or a token.
Remarks:
An exception is thrown if the request has no Authorization header.
get_proxy_credentials
Get the authentication scheme and information of the request's Proxy-Authorization header.
void http_request::get_proxy_credentials(string&inout scheme, string&inout auth_info) const;
Arguments:
- string&inout scheme: receives the scheme.
- string&inout auth_info: receives the information following the scheme.
Remarks:
An exception is thrown if the request has no Proxy-Authorization header.
remove_credentials
Remove the request's Authorization header.
void http_request::remove_credentials();
remove_proxy_credentials
Remove the request's Proxy-Authorization header.
void http_request::remove_proxy_credentials();
set_cookies
Add cookies to the request's Cookie header.
void http_request::set_cookies(const name_value_collection&inout cookies);
Arguments:
- const name_value_collection&inout cookies: the names and values of the cookies to send.
set_credentials
Set the request's Authorization header.
void http_request::set_credentials(const string&in scheme, const string&in auth_info);
Arguments:
- const string&in scheme: the authentication scheme, such as
Bearer. - const string&in auth_info: the information following the scheme, such as a token.
Remarks:
For username and password authentication, http_credentials can create this header for you.
set_proxy_credentials
Set the request's Proxy-Authorization header.
void http_request::set_proxy_credentials(const string&in scheme, const string&in auth_info);
Arguments:
- const string&in scheme: the authentication scheme.
- const string&in auth_info: the information following the scheme.
Properties
chunked_transfer_encoding
Whether the message's body is sent with chunked transfer encoding.
bool http_request::chunked_transfer_encoding;
Remarks:
Setting this to true sets the Transfer-Encoding header to chunked, which also removes any Content-Length header.
content_length
The length of the message's body in bytes, from its Content-Length header.
int64 http_request::content_length;
Remarks:
This is HTTP_UNKNOWN_CONTENT_LENGTH, -1, if the header isn't set, and setting it to that removes the header.
content_type
The media type of the message's body, from its Content-Type header, such as text/html or application/json.
string http_request::content_type;
Remarks:
This is HTTP_UNKNOWN_CONTENT_TYPE, an empty string, if the header isn't set.
expect_continue
Whether the request has an Expect: 100-continue header, which asks the server to confirm it will accept the request before its body is sent.
bool http_request::expect_continue;
Remarks:
After sending such a request, use http_client::peek_response() to find out whether to send the body.
has_content_length
Whether the message has a Content-Length header.
const bool http_request::has_content_length;
has_credentials
Whether the request has an Authorization header.
const bool http_request::has_credentials;
has_proxy_credentials
Whether the request has a Proxy-Authorization header.
const bool http_request::has_proxy_credentials;
host
The host the request is for, from its Host header.
string http_request::host;
Remarks:
Calling set_host(host, port) sets the host and port together, leaving the port out of the header when it is 80.
keep_alive
Whether the connection should stay open after the message, from its Connection header.
bool http_request::keep_alive;
Remarks:
Setting this sets the Connection header to Keep-Alive or Close. When the header isn't set, HTTP/1.1 messages keep the connection alive and HTTP/1.0 messages don't.
method
The method of the request, such as HTTP_GET, HTTP_POST or HTTP_PUT.
string http_request::method;
transfer_encoding
The transfer encoding of the message, from its Transfer-Encoding header.
string http_request::transfer_encoding;
Remarks:
This is usually HTTP_IDENTITY_TRANSFER_ENCODING, meaning the body is sent as is, or HTTP_CHUNKED_TRANSFER_ENCODING, meaning it is sent in chunks so its length doesn't have to be known in advance.
uri
What the request asks the server for, usually the path and query of a URL such as /docs/?search=sound.
string http_request::uri;
Remarks:
When requesting through a proxy, this is the complete URL instead.
version
The HTTP version of the message, such as HTTP/1.1.
string http_request::version;
Remarks:
The HTTP_1_0 and HTTP_1_1 constants hold the versions. New messages use HTTP/1.0 unless given a version, except that http_request's constructor taking a method defaults to HTTP/1.1.
http_response
An HTTP response, with its status, reason, version and headers.
http_response();
http_response(const http_response&in other);
http_response(http_status status);
http_response(http_status status, const string&in reason);
http_response(const string&in version, http_status status, const string&in reason);
http_response(const string&in version, http_status status);
http_response(\{\{string, string}, ...});
Arguments:
const http_response&in other (2): a response to copy.
http_status status (3, 4, 5, 6): the status of the response, a value of the http_status enum.
const string&in reason (4, 5): the reason phrase of the response. Without it, the standard phrase for the status is used.
const string&in version (5, 6): the HTTP version of the response.
\{\{string, string}, ...} (7): the names and values of the response's headers, each pair in its own set of braces.
Remarks:
http_response objects are filled in by http_client::receive_response(), returned by http::response_headers, and given to url_get() and its relatives.
An http_response is an internet_message_header holding the response's headers, so a header is read by indexing it, as in resp["Content-Type"], and it has every method of internet_message_header and name_value_collection as well as the ones listed here. The response doesn't include its body, which is read from the stream returned by http_client::receive_response().
Example:
void main() {
http_response resp;
string body = url_get("https://nvgt.dev", resp);
string info = resp.version + " " + resp.status + " " + resp.reason + "\ntype: " + resp.content_type + "\nlength: " + body.length();
for (uint i = 0; i < resp.size(); i++) info += "\n" + resp.name_at(i) + ": " + resp.value_at(i);
alert("Response", info);
}
Methods
set_status_and_reason
Set the status and reason phrase of the response together.
void http_response::set_status_and_reason(http_status status, const string&in reason);void http_response::set_status_and_reason(http_status status);
Arguments:
- http_status status: the status, a value of the http_status enum.
- const string&in reason (1): the reason phrase. Without it, the standard phrase for the status is used.
Properties
chunked_transfer_encoding
Whether the message's body is sent with chunked transfer encoding.
bool http_response::chunked_transfer_encoding;
Remarks:
Setting this to true sets the Transfer-Encoding header to chunked, which also removes any Content-Length header.
content_length
The length of the message's body in bytes, from its Content-Length header.
int64 http_response::content_length;
Remarks:
This is HTTP_UNKNOWN_CONTENT_LENGTH, -1, if the header isn't set, and setting it to that removes the header.
content_type
The media type of the message's body, from its Content-Type header, such as text/html or application/json.
string http_response::content_type;
Remarks:
This is HTTP_UNKNOWN_CONTENT_TYPE, an empty string, if the header isn't set.
has_content_length
Whether the message has a Content-Length header.
const bool http_response::has_content_length;
keep_alive
Whether the connection should stay open after the message, from its Connection header.
bool http_response::keep_alive;
Remarks:
Setting this sets the Connection header to Keep-Alive or Close. When the header isn't set, HTTP/1.1 messages keep the connection alive and HTTP/1.0 messages don't.
reason
The reason phrase of the response, such as OK or Not Found.
string http_response::reason;
status
The status of the response, a value of the http_status enum, such as HTTP_OK (200) or HTTP_NOT_FOUND (404).
http_status http_response::status;
Remarks:
Calling set_status(string) sets the status from a string such as 404.
transfer_encoding
The transfer encoding of the message, from its Transfer-Encoding header.
string http_response::transfer_encoding;
Remarks:
This is usually HTTP_IDENTITY_TRANSFER_ENCODING, meaning the body is sent as is, or HTTP_CHUNKED_TRANSFER_ENCODING, meaning it is sent in chunks so its length doesn't have to be known in advance.
version
The HTTP version of the message, such as HTTP/1.1.
string http_response::version;
Remarks:
The HTTP_1_0 and HTTP_1_1 constants hold the versions. New messages use HTTP/1.0 unless given a version, except that http_request's constructor taking a method defaults to HTTP/1.1.
https_client
A connection to an HTTPS server, which sends http_request objects and receives http_response objects over TLS.
https_client(const string&in host, uint16 port = 443);
Arguments:
const string&in host: the host to connect to, such as
nvgt.dev.uint16 port = 443: the port to connect to.
Remarks:
For most HTTP requests, the http class is far easier to use, as it runs the request in the background, follows redirects, handles authentication and works with both http and https URLs. This lower level class is for when more control over the request and the connection is needed.
https_client has exactly the same methods and properties as http_client, documented there, except that it connects with TLS and its secure property is true. It converts to an http_client implicitly, and an http_client that is really an https_client can be cast back with cast<https_client@>().
Example:
void main() {
https_client client("nvgt.dev");
http_request req(HTTP_GET, "/");
client.send_request(req);
http_response resp;
datastream@ body = client.receive_response(resp);
alert("Status " + resp.status, body.read().length() + " bytes received over " + (client.secure? "a secure" : "an insecure") + " connection.");
}
internet_message_header
The headers of an internet message such as an HTTP request or an email, a name_value_collection that can also be read from and written to streams.
internet_message_header();internet_message_header(const internet_message_header&in other);internet_message_header(\{\{string, string}, ...});
Arguments:
- const internet_message_header&in other (2): headers to copy.
- \{\{string, string}, ...} (3): the names and values of the headers, each pair in its own set of braces.
Remarks:
This is a name_value_collection with every one of its methods, plus the ones listed here, and is the base of http_request and http_response. It can be created from an initialization list of names and values like a name_value_collection.
An internet_message_header can be cast to an http_request or http_response with cast<http_request@>() if that is what it really is, and converts to a name_value_collection implicitly.
Methods
get_decoded
Get the value of a header, decoding any RFC 2047 encoded words in it, as used by email headers with characters outside ASCII.
string internet_message_header::get_decoded(const string&in name, const string&in default_value = "");
Arguments:
- const string&in name: the name of the header.
- const string&in default_value = "": the value to return if the header isn't there.
Returns:
string: the decoded value, or default_value.
has_token
Find out whether a header that holds a comma separated list of tokens contains a token.
bool internet_message_header::has_token(const string&in name, const string&in token);
Arguments:
- const string&in name: the name of the header, such as
Connection. - const string&in token: the token to look for, such as
Upgrade, case insensitively.
Returns:
bool: true if the header exists and contains the token, false otherwise.
read
Read headers from a stream in the format of an internet message, adding them to the collection.
bool internet_message_header::read(datastream@ stream);
Arguments:
- datastream@ stream: the datastream to read from.
Returns:
bool: true if the headers were read, false if the stream can't be read from or the headers were malformed or exceeded the limits.
Remarks:
Reading stops at the blank line that ends the headers, or the end of the stream.
write
Write the headers to a stream in the format of an internet message, one Name: value line for each, without the blank line that ends them.
bool internet_message_header::write(datastream@ stream) const;
Arguments:
- datastream@ stream: the datastream to write to.
Returns:
bool: true if the headers were written, false if the stream can't be written to or writing failed.
Properties
auto_decode
Whether header values encoded as described by RFC 2047, such as =?UTF-8?B?...?=, are decoded automatically as they are read.
bool internet_message_header::auto_decode;
Remarks:
This defaults to false. get_decoded() decodes a single header either way.
field_limit
The maximum number of headers read() accepts.
int internet_message_header::field_limit;
Remarks:
This defaults to 100, and protects against a peer sending endless headers. 0 means no limit.
name_length_limit
The maximum length of a header name read() accepts.
int internet_message_header::name_length_limit;
Remarks:
This defaults to 256.
value_length_limit
The maximum length of a header value read() accepts.
int internet_message_header::value_length_limit;
Remarks:
This defaults to 8192.
ip_address
An IPv4 or IPv6 address.
ip_address();
ip_address(spec::ip_address_family family);
ip_address(const string&in addr);
ip_address(const string&in addr, spec::ip_address_family family);
ip_address(const spec::ip_address&in other);
Arguments:
spec::ip_address_family family (2, 4): the family of the address. Without an address, this creates the wildcard address of the family,
0.0.0.0or::.const string&in addr (3, 4): the address to parse, such as
192.168.1.10or::1.const spec::ip_address&in other (5): an address to copy.
Remarks:
This class is in the spec namespace, so scripts write it as spec::ip_address unless they have a using namespace spec; statement.
The default constructor creates the IPv4 wildcard address 0.0.0.0. Constructing an ip_address from a string parses it and throws an exception if it isn't a valid address. Host names aren't resolved, use dns_resolve() or dns_resolve_single() for those, or spec::parse_ip_address() to parse without an exception.
An ip_address converts to its string form implicitly, though as it has no + operator of its own, it must follow a string when concatenated, as in "address: " + addr, or be converted with string(addr). Addresses can be compared and sorted, and the &, |, ^ and ~ operators work on their bits, which is useful with network masks.
Example:
void main() {
spec::ip_address local("192.168.1.10");
spec::ip_address netmask("255.255.255.0");
spec::ip_address subnet = local & netmask;
spec::ip_address loopback("::1");
alert("IP addresses", "The address " + local + " is in network " + subnet + " with a prefix length of " + netmask.prefix_length + ".\n" + loopback + " is " + (loopback.is_v6? "IPv6" : "IPv4") + (loopback.is_loopback? " loopback." : "."));
}
Methods
mask
Mask the address, keeping only the bits that are set in a mask.
void ip_address::mask(const spec::ip_address&in mask);void ip_address::mask(const spec::ip_address&in mask, const spec::ip_address&in set);
Arguments:
- const spec::ip_address&in mask: the mask to apply, such as 255.255.255.0.
- const spec::ip_address&in set (2): an address whose bits replace the bits removed by the mask.
Remarks:
This only works with IPv4 addresses.
Properties
family
The family of the address, a value of the spec::ip_address_family enum.
const spec::ip_address_family ip_address::family;
is_broadcast
Whether this is the IPv4 broadcast address 255.255.255.255.
const bool ip_address::is_broadcast;
Remarks:
Only the limited broadcast address counts, not the broadcast addresses of particular networks.
is_global_multicast
Whether this is a global multicast address, 224.0.1.0 to 238.255.255.255 for IPv4 or ff0f::/16 for IPv6.
const bool ip_address::is_global_multicast;
is_IPV4_compatible
Whether this is an IPv4 compatible IPv6 address, an IPv4 address in the last 4 bytes of an IPv6 address whose other bytes are 0, or any IPv4 address.
const bool ip_address::is_IPV4_compatible;
is_IPV4_mapped
Whether this is an IPv4 mapped IPv6 address, of the form ::ffff:a.b.c.d, or any IPv4 address.
const bool ip_address::is_IPV4_mapped;
is_link_local
Whether this is a link local address, 169.254.0.0/16 for IPv4 or fe80::/10 for IPv6, which only works on the local network segment.
const bool ip_address::is_link_local;
is_link_local_multicast
Whether this is a link local multicast address, 224.0.0.0/24 for IPv4 or ff02::/16 for IPv6.
const bool ip_address::is_link_local_multicast;
is_loopback
Whether this is a loopback address, which always refers to the computer itself, such as 127.0.0.1 or ::1.
const bool ip_address::is_loopback;
is_multicast
Whether this is a multicast address, 224.0.0.0 to 239.255.255.255 for IPv4 or ff00::/8 for IPv6.
const bool ip_address::is_multicast;
is_node_local_multicast
Whether this is a node local multicast address, which is always false for IPv4 and ff01::/16 for IPv6.
const bool ip_address::is_node_local_multicast;
is_org_local_multicast
Whether this is an organization local multicast address, 239.192.0.0/16 for IPv4 or ff08::/16 for IPv6.
const bool ip_address::is_org_local_multicast;
is_site_local
Whether this is a site local address, meaning a private network address such as 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16 for IPv4, or fec0::/10 or a unique local fc00::/7 address for IPv6.
const bool ip_address::is_site_local;
is_site_local_multicast
Whether this is a site local multicast address, 239.255.0.0/16 for IPv4 or ff05::/16 for IPv6.
const bool ip_address::is_site_local_multicast;
is_unicast
Whether this is a unicast address, meaning one that is neither the wildcard, broadcast nor a multicast address.
const bool ip_address::is_unicast;
is_v4
Whether this is an IPv4 address.
const bool ip_address::is_v4;
is_v6
Whether this is an IPv6 address.
const bool ip_address::is_v6;
is_well_known_multicast
Whether this is a well known multicast address, 224.0.0.0/8 for IPv4 or ff0x::/16 for IPv6.
const bool ip_address::is_well_known_multicast;
is_wildcard
Whether this is the wildcard address, 0.0.0.0 or ::, which a server binds to in order to listen on every network interface.
const bool ip_address::is_wildcard;
prefix_length
The number of leading bits that are set, which is the prefix length of a network mask such as 24 for 255.255.255.0.
const uint ip_address::prefix_length;
scope
The scope identifier of an IPv6 address, which identifies the network interface a link local address belongs to, or 0 for IPv4 addresses.
const uint ip_address::scope;
mail_message
An email message, with its sender, recipients, subject, content and attachments, for sending with smtp_client.
mail_message();
Remarks:
Methods that can fail don't throw exceptions, instead the reason is stored in last_error.
The content can be plain text set with set_content(), or HTML set with set_html_content() along with a plain text version for mail programs that can't show HTML. Files and strings can be attached, and images can be embedded in the HTML with add_inline_attachment_file(), which returns the content ID to refer to them by, as in <img src="cid:logo.png@nvgt.mail">.
Example:
void main() {
mail_message msg;
msg.set_sender("Game Server <server@example.com>");
msg.add_recipient("player@example.com");
msg.add_recipient("admin@example.com", RECIPIENT_BCC);
msg.set_subject("Your weekly stats");
msg.set_html_content("<h1>Great week!</h1><p>You played 12 matches.</p>", "Great week! You played 12 matches.");
msg.add_attachment_string("stats.csv", "matches,wins\n12,7\n", "text/csv");
msg.set_priority(MAIL_PRIORITY_HIGH);
mail_recipient@[]@ recipients = msg.get_recipients();
alert("Message", msg.subject + " from " + msg.sender + " to " + recipients.length() + " recipients.");
}
Methods
add_attachment_file
Attach a file to the message.
bool mail_message::add_attachment_file(const string&in name, const string&in path);
Arguments:
- const string&in name: the name the attachment is shown with.
- const string&in path: the path of the file to attach.
Returns:
bool: true if the file was attached, false if it couldn't be read, with the reason in last_error.
add_attachment_string
Attach data from a string to the message, as though it were a file.
bool mail_message::add_attachment_string(const string&in name, const string&in content, const string&in media_type = "application/octet-stream");
Arguments:
- const string&in name: the name the attachment is shown with, such as
scores.csv. - const string&in content: the data to attach.
- const string&in media_type = "application/octet-stream": the media type of the data, such as
text/csv.
Returns:
bool: true if the data was attached, false otherwise, with the reason in last_error.
add_header
Add a header to the message.
void mail_message::add_header(const string&in name, const string&in value);
Arguments:
- const string&in name: the name of the header, such as
X-Game-Version. - const string&in value: the value of the header.
add_inline_attachment_file
Attach a file to the message so it can be shown within its HTML content, such as an image.
string mail_message::add_inline_attachment_file(const string&in path, const string&in content_id = "");
Arguments:
- const string&in path: the path of the file to attach.
- const string&in content_id = "": the content ID to give the attachment. If empty, the filename followed by
@nvgt.mailis used.
Returns:
string: the content ID, which the HTML refers to as cid: followed by the ID, or an empty string if the file couldn't be attached, with the reason in last_error.
add_inline_attachment_string
Attach data from a string to the message so it can be shown within its HTML content.
string mail_message::add_inline_attachment_string(const string&in content, const string&in media_type, const string&in content_id);
Arguments:
- const string&in content: the data to attach.
- const string&in media_type: the media type of the data, such as
image/png. - const string&in content_id: the content ID to give the attachment. If empty,
inline@nvgt.mailis used, so give each attachment a unique ID.
Returns:
string: the content ID, or an empty string if the data couldn't be attached, with the reason in last_error.
add_recipient
Add a recipient to the message.
void mail_message::add_recipient(const mail_recipient&in recipient);void mail_message::add_recipient(const string&in address, mail_recipient_type type = RECIPIENT_TO);
Arguments:
- const mail_recipient&in recipient (1): the recipient to add.
- const string&in address (2): the address of the recipient.
- mail_recipient_type type = RECIPIENT_TO (2): whether the recipient is a primary recipient, a carbon copy or a blind carbon copy, a value of the mail_recipient_type enum.
get_header
Get a header of the message.
string mail_message::get_header(const string&in name) const;
Arguments:
- const string&in name: the name of the header.
Returns:
string: the value of the header, or an empty string if the message doesn't have it.
get_recipients
Get the recipients of the message.
array<mail_recipient@>@ mail_message::get_recipients() const;
Returns:
array<mail_recipient@>@: copies of the message's recipients.
set_content
Add text content to the message.
void mail_message::set_content(const string&in content, const string&in content_type = "text/plain");
Arguments:
- const string&in content: the content.
- const string&in content_type = "text/plain": the media type of the content, such as
text/plainortext/html.
Remarks:
Each call adds another part to the message, so this should usually be called once. For HTML, set_html_content() also includes a plain text version.
set_html_content
Set the content of the message to HTML, with a plain text alternative for mail programs that can't display HTML.
void mail_message::set_html_content(const string&in html, const string&in plain_alternative = "");
Arguments:
- const string&in html: the HTML content.
- const string&in plain_alternative = "": the plain text version. If empty, a note that the message needs HTML support to view is used.
Remarks:
The parts are added to the message when it is sent.
set_priority
Set the priority of the message, which mail programs may show or sort by.
void mail_message::set_priority(mail_priority priority);
Arguments:
- mail_priority priority: the priority, a value of the mail_priority enum.
Remarks:
This sets the X-Priority and Importance headers.
set_read_receipt
Ask the recipient's mail program to send a read receipt.
void mail_message::set_read_receipt(const string&in address);
Arguments:
- const string&in address: the address the receipt should be sent to.
Remarks:
This sets both the Disposition-Notification-To and Return-Receipt-To headers. Many mail programs ask the user first or ignore the request.
set_sender
Set who the message is from.
void mail_message::set_sender(const string&in address);
Arguments:
- const string&in address: the sender's address, optionally with a name, such as
Sam <sam@example.com>.
set_subject
Set the subject of the message.
void mail_message::set_subject(const string&in subject);
Arguments:
- const string&in subject: the subject, which can contain any characters.
Properties
content
The content of a message that consists of a single part, such as one returned by parse_email_message().
const string mail_message::content;
disposition_notification_to
The address a read receipt should be sent to, from the Disposition-Notification-To header.
string mail_message::disposition_notification_to;
in_reply_to
The message_id of the message this one replies to, from its In-Reply-To header.
string mail_message::in_reply_to;
last_error
A description of why the last operation that can fail did, or an empty string if it succeeded.
const string mail_message::last_error;
message_id
The unique identifier of the message, from its Message-ID header.
string mail_message::message_id;
Remarks:
Replies refer to a message by this identifier, see in_reply_to and references.
priority
The priority of the message, from MAIL_PRIORITY_HIGHEST (1) to MAIL_PRIORITY_LOWEST (5), or MAIL_PRIORITY_NORMAL (3) if none was set.
const int mail_message::priority;
Remarks:
Use set_priority() to change it.
references
The message IDs of the earlier messages in the conversation, separated by spaces, from the References header.
string mail_message::references;
Remarks:
Mail programs use this and in_reply_to to group messages into threads.
reply_to
The address replies to the message should go to, if different from the sender, from the Reply-To header.
string mail_message::reply_to;
return_receipt_to
The address a delivery receipt should be sent to, from the Return-Receipt-To header.
string mail_message::return_receipt_to;
sender
Who the message is from.
const string mail_message::sender;
Remarks:
Use set_sender() to change it.
subject
The subject of the message.
const string mail_message::subject;
Remarks:
Use set_subject() to change it.
mail_recipient
A recipient of a mail_message, with their address, name and type.
mail_recipient();mail_recipient(mail_recipient_type type, const string&in address, const string&in real_name = "");
Arguments:
- mail_recipient_type type (2): whether this is a primary recipient, a carbon copy or a blind carbon copy, a value of the mail_recipient_type enum.
- const string&in address (2): the email address of the recipient.
- const string&in real_name = "" (2): the name of the recipient, shown by mail programs alongside the address.
Remarks:
A recipient created without arguments is a primary recipient with no address.
Properties
address
The email address of the recipient.
string mail_recipient::address;
real_name
The name of the recipient, shown by mail programs alongside the address.
string mail_recipient::real_name;
type
Whether this is a primary recipient, a carbon copy or a blind carbon copy, a value of the mail_recipient_type enum.
mail_recipient_type mail_recipient::type;
name_value_collection
A list of names and values, such as the headers of an HTTP request or the cookies of a website.
name_value_collection();
name_value_collection(const name_value_collection&in other);
name_value_collection(\{\{string, string}, ...});
Arguments:
const name_value_collection&in other (2): a collection to copy.
\{\{string, string}, ...} (3): the names and values to start with, each pair in its own set of braces.
Remarks:
Names are case insensitive, so c["content-type"] and c["Content-Type"] are the same entry, and a name can appear more than once. A collection can be created from an initialization list of name and value pairs, as in name_value_collection headers = \{\{"Accept", "text/html"}, {"Accept-Language", "en"\}\};.
Indexing the collection with a name gets or sets its value, but reading a name that isn't there throws an exception, use get() with a default value to avoid that. Entries keep their order, and name_at() and value_at() access them by position.
internet_message_header, and through it http_request and http_response, are name_value_collections with more methods, so everything here works with them too. A name_value_collection that is really one of those can be cast to it with cast<internet_message_header@>().
Example:
void main() {
name_value_collection c = \{\{"Name", "Sam"}, {"Game", "NVGT"\}\};
c["score"] = "1500";
c.add("game", "BGT");
string info = "name: " + c["name"] + "\nlevel: " + c.get("level", "unknown") + "\n" + c.size() + " entries:";
for (uint i = 0; i < c.size(); i++) info += "\n" + c.name_at(i) + " = " + c.value_at(i);
alert("Collection", info);
}
Methods
add
Add a name and value to the collection, even if the name is already in it.
void name_value_collection::add(const string&in name, const string&in value);
Arguments:
- const string&in name: the name to add.
- const string&in value: the value to add.
Remarks:
Some headers, such as Set-Cookie, may appear more than once, which this allows.
clear
Remove every entry from the collection.
void name_value_collection::clear();
empty
Find out whether the collection is empty.
bool name_value_collection::empty() const;
Returns:
bool: true if the collection has no entries, false otherwise.
erase
Remove every entry with a name.
void name_value_collection::erase(const string&in name);
Arguments:
- const string&in name: the name to remove, case insensitively.
exists
Find out whether a name is in the collection.
bool name_value_collection::exists(const string&in name) const;
Arguments:
- const string&in name: the name to look for, case insensitively.
Returns:
bool: true if the collection has an entry with the name, false otherwise.
get
Get the value of a name, or a default value if it isn't in the collection.
string name_value_collection::get(const string&in name, const string&in default_value = "") const;
Arguments:
- const string&in name: the name to look up, case insensitively.
- const string&in default_value = "": the value to return if the name isn't in the collection.
Returns:
string: the value of the first entry with the name, or default_value.
Remarks:
Indexing the collection, as in c["name"], also returns the value of a name, but throws an exception if it isn't there.
name_at
Get the name of an entry by its position.
const string& name_value_collection::name_at(uint index) const;
Arguments:
- uint index: the position of the entry, from 0 to size() - 1.
Returns:
const string&: the name of the entry.
Remarks:
An exception is thrown if the index is out of range. Together with value_at() and size(), this lets every entry be listed.
secure_erase
Remove every entry with a name, overwriting their values in memory first.
void name_value_collection::secure_erase(const string&in name);
Arguments:
- const string&in name: the name to remove, case insensitively.
Remarks:
This is useful for values such as passwords and tokens, which shouldn't be left in memory after they are removed.
set
Set the value of a name, replacing the existing value if the name is already in the collection.
void name_value_collection::set(const string&in name, const string&in value);
Arguments:
- const string&in name: the name to set. Names are case insensitive.
- const string&in value: the value to set.
Remarks:
Assigning to an index, as in c["name"] = "value";, does the same.
size
Get the number of entries in the collection.
uint64 name_value_collection::size() const;
Returns:
uint64: the number of names and values, counting names that appear more than once.
value_at
Get the value of an entry by its position.
const string& name_value_collection::value_at(uint index) const;
Arguments:
- uint index: the position of the entry, from 0 to size() - 1.
Returns:
const string&: the value of the entry.
Remarks:
An exception is thrown if the index is out of range.
network
methods
connect
Attempt to establish a connection with a server, only works when set up as a client.
uint64 network::connect(const string&in hostname, uint16 port);
Arguments:
- const string&in hostname: the hostname/IP address to connect to.
- uint16 port: the port to use.
Returns:
uint64: the peer ID of the connection, or 0 on error.
destroy
Destroys the network object, freeing all its resources, active connections, etc.
void network::destroy();
disconnect_peer
Tell a peer to disconnect and completely disregard its message queue. This means that the peer will be told to disconnect without sending any of its queued packets (if any).
bool network::disconnect_peer(uint peer_id);
Arguments:
- uint peer_id: the ID of the peer to disconnect.
Returns:
bool: true on success, false otherwise.
disconnect_peer_forcefully
Forcefully disconnect a peer. Unlike network::disconnect_peer(), this function doesn't send any sort of notification of the disconnection to the remote peer, instead it closes the connection immediately.
bool network::disconnect_peer_forcefully(uint peer_id);
Arguments:
- uint peer_id: the ID of the peer to disconnect.
Returns:
bool: true on success, false otherwise.
disconnect_peer_softly
Send a disconnect packet for a peer after sending any remaining packets in the queue and notifying the peer.
bool network::disconnect_peer_softly(uint peer_id);
Arguments:
- uint peer_id: the ID of the peer to disconnect.
Returns:
bool: true on success, false otherwise.
get_peer_address
Returns the IP address of a particular peer.
string network::get_peer_address(uint peer_id);
Arguments:
- uint peer_id: the ID of the peer to check.
Returns:
string: the IP address of the specified peer.
get_peer_list
Return a list of all peer ID's currently connected to the server.
uint[]@ network::get_peer_list();
Returns:
uint[]@: a handle to an array containing the ID of every peer currently connected to the server.
request
This is the function you'll probably be calling the most when you're dealing with the network object in NVGT. It checks if an event has occurred since the last time it checked. If it has, it returns you a network_event handle with info about it.
network_event@ network::request(uint timeout = 0);
Arguments:
- uint timeout = 0: an optional timeout on your packet receiving (see remarks for more information).
Returns:
network_event@: a handle to a network_event object containing info about the last received event.
Remarks:
The timeout parameter is in milliseconds, and it determines how long Enet will wait for new packets before returning control back to the calling application. However, if it receives a packet within the timeout period, it will return and you'll be handed the packet straight away.
send
Attempt to send a packet over the network.
bool network::send(uint peer_id, const string&in message, uint8 channel, bool reliable = true);
Arguments:
- uint peer_id: the ID of the peer to send to (specify 1 to send to the server from a client).
- const string&in message: the message to send.
- uint8 channel: the channel to send the message on (see the main networking documentation for more details).
- bool reliable = true: whether or not the packet should be sent reliably or not (see the main networking documentation for more details).
Returns:
bool: true if the packet was successfully sent, false otherwise.
send_reliable
Attempt to send a packet over the network reliably.
bool network::send_reliable(uint peer_id, const string&in message, uint8 channel);
Arguments:
- uint peer_id: the ID of the peer to send to (specify 1 to send to the server from a client).
- const string&in message: the message to send.
- uint8 channel: the channel to send the message on (see the main networking documentation for more details).
Returns:
bool: true if the packet was successfully sent, false otherwise.
send_unreliable
Attempt to send a packet over the network unreliably.
bool network::send_unreliable(uint peer_id, const string&in message, uint8 channel);
Arguments:
- uint peer_id: the ID of the peer to send to (specify 1 to send to the server from a client).
- const string&in message: the message to send.
- uint8 channel: the channel to send the message on (see the main networking documentation for more details).
Returns:
bool: true if the packet was successfully sent, false otherwise.
set_bandwidth_limits
Set the incoming and outgoing bandwidth limits of the server (in bytes-per-second).
void network::set_bandwidth_limits(uint incoming, uint outgoing);
Arguments:
- uint incoming: the maximum number of allowed incoming bytes per second.
- uint outgoing: the maximum number of allowed outgoing bytes per second.
setup_client
Sets up the network object as a client.
bool network::setup_client(uint8 max_channels, uint16 max_peers);
Arguments:
- uint8 max_channels: the maximum number of channels used on the connection (up to 255).
- uint16 max_peers: the maximum number of peers allowed by the connection (maximum is 65535).
Returns:
bool: true if the client was successfully set up, false otherwise.
setup_local_server
Sets up the network object as a local server on localhost.
bool network::setup_local_server(uint16 bind_port, uint8 max_channels, uint16 max_peers);
Arguments:
- uint16 bind_port: the port to bind the server to.
- uint8 max_channels: the maximum number of channels used on the connection (up to 255).
- uint16 max_peers: the maximum number of peers allowed by the connection (maximum is 65535).
Returns:
bool: true if the server was successfully set up, false otherwise.
setup_server
Sets up the network object as a server.
bool network::setup_server(uint16 bind_port, uint8 max_channels, uint16 max_peers);
Arguments:
- uint16 bind_port: the port to bind the server to.
- uint8 max_channels: the maximum number of channels used on the connection (up to 255).
- uint16 max_peers: the maximum number of peers allowed by the connection (maximum is 65535).
Returns:
bool: true if the server was successfully set up, false otherwise.
properties
active
Determine if the network object is active (e.g. a setup_* method has successfully been called on it).
bool network::active;
bytes_received
The number of bytes this network object has received since being set up.
uint network::bytes_received;
bytes_sent
The number of bytes this network object has sent since being set up.
uint network::bytes_sent;
connected_peers
The number of peers currently connected to the server.
uint network::connected_peers;
network_event
This class represents an event received with the network object's request() method. It contains information such as the the ID of the peer that sent the event, the message the event was sent on, and the actual packet data itself.
methods
opAssign
This class implements the opAssign() operator overload, meaning it can be assigned with the "=" operator to another network_event.
network_event@ opAssign(network_event@ e);
properties
channel
The channel this event was sent on. See the main networking documentation for more information.
uint network_event::channel;
message
The data associated with this event (AKA the packet).
string network_event::message;
peer_id
The peer ID of the connection this event came from. See the main networking documentation for more information.
uint network_event::peer_id;
type
The type of the network event (see event types for more information).
int network_event::type;
smtp_client
Send email through an SMTP server.
smtp_client();
Remarks:
Set the host, and if needed the port and use_ssl, then call connect(), log in if the server needs it with login(), and send mail_message objects with send_message() or send_messages(). Every method blocks until the server responds, and instead of throwing exceptions they return false on failure, with a description of the problem in last_error.
use_ssl encrypts the connection, using TLS from the very first byte on port 465 and STARTTLS during connect() on other ports such as 587.
Many email providers require an app password, or OAuth2 through login_oauth2(), rather than the account's normal password.
Example:
void main() {
smtp_client smtp;
smtp.host = "smtp.example.com";
smtp.port = 587;
smtp.use_ssl = true;
if (!smtp.connect() or !smtp.login("me@example.com", "app password")) {
alert("Error", smtp.last_error);
return;
}
mail_message msg;
msg.set_sender("me@example.com");
msg.add_recipient("friend@example.com");
msg.set_subject("High score");
msg.set_content("I just scored 1500 points!");
if (!smtp.send_message(msg)) alert("Error", smtp.last_error);
smtp.close();
}
Methods
close
Say goodbye to the server and close the connection.
void smtp_client::close();
connect
Connect to the server and greet it.
bool smtp_client::connect();
Returns:
bool: true if the connection was made, false otherwise, with the reason in last_error.
Remarks:
Any existing connection is closed first.
login
Log in to the server.
bool smtp_client::login(const string&in username, const string&in password, smtp_auth_method method = SMTP_AUTH_LOGIN);
Arguments:
- const string&in username: the username, usually the email address.
- const string&in password: the password, which for many providers must be an app password.
- smtp_auth_method method = SMTP_AUTH_LOGIN: how to authenticate, a value of the smtp_auth_method enum. The server must support the method chosen, which query_server_capabilities() can show.
Returns:
bool: true if the server accepted the login, false otherwise, with the reason in last_error.
login_oauth2
Log in to the server with an OAuth2 access token, which providers such as Gmail and Outlook prefer.
bool smtp_client::login_oauth2(const string&in username, const string&in access_token);
Arguments:
- const string&in username: the email address to log in as.
- const string&in access_token: an OAuth2 access token for the account, obtained from the provider.
Returns:
bool: true if the server accepted the login, false otherwise, with the reason in last_error.
query_server_capabilities
Ask the server which extensions and authentication methods it supports.
string smtp_client::query_server_capabilities();
Returns:
string: the server's response to the EHLO command, with one capability on each line, such as AUTH LOGIN PLAIN and STARTTLS, or an empty string if it failed.
send_message
Send an email.
bool smtp_client::send_message(mail_message@ message);
Arguments:
- mail_message@ message: the message to send, which needs a sender and at least one recipient.
Returns:
bool: true if the server accepted the message, false otherwise, with the reason in last_error.
send_messages
Send several emails over the same connection.
bool smtp_client::send_messages(array<mail_message@>@ messages);
Arguments:
- array<mail_message@>@ messages: the messages to send.
Returns:
bool: true if the server accepted every message, false if one failed, with the reason in last_error. The messages before it were sent, and the ones after it weren't.
Properties
host
The host name of the SMTP server, such as smtp.example.com.
string smtp_client::host;
is_authenticated
Whether the client has logged in since it connected.
const bool smtp_client::is_authenticated;
is_connected
Whether the client is connected to the server.
const bool smtp_client::is_connected;
last_error
A description of why the last operation failed, or an empty string if it succeeded.
const string smtp_client::last_error;
port
The port of the SMTP server.
int smtp_client::port;
Remarks:
This defaults to 25. Most servers that accept mail from users listen on 587.
server_capabilities
The server's capabilities, as last returned by query_server_capabilities().
const string smtp_client::server_capabilities;
timeout
How many milliseconds to wait for the server to respond before giving up.
int smtp_client::timeout;
Remarks:
This defaults to 30000, 30 seconds, and takes effect on the next connect().
use_ssl
Whether to encrypt the connection with TLS.
bool smtp_client::use_ssl;
Remarks:
This defaults to false. On port 465 the connection is encrypted from the very first byte, while on any other port, such as 587, it is upgraded with STARTTLS during connect(), which fails if the server doesn't support it. Set it before calling connect().
socket
The base of NVGT's sockets, with the properties and options every socket has.
socket();socket(const socket&in sock);
Arguments:
- const socket&in sock (2): a socket to share the underlying socket of.
Remarks:
For networking between the players of a game, the network class is usually a better fit, as it handles connections, reliable and unreliable messages and channels for you.
A socket object on its own is a null socket. Sockets that are actually used are stream_socket and web_socket, which have every method and property of socket as well as their own, and can be made from a socket that really is one of them.
Copying a socket, with the copy constructor or assignment, doesn't copy the connection. Both objects then refer to the same underlying socket, which closes when the last of them is destroyed or close() is called.
Methods
close
Close the socket.
void socket::close();
Remarks:
For a stream socket this ends the connection without the orderly shutdown that shutdown() performs.
get_linger
Get whether closing the socket waits for unsent data to be delivered.
void socket::get_linger(bool&out on, int&out seconds);
Arguments:
- bool&out on: receives whether the socket lingers when closed.
- int&out seconds: receives the longest time it lingers for.
get_option
Get a socket option of the operating system's socket API.
void socket::get_option(int level, int option, int&out value) const;void socket::get_option(int level, int option, uint&out value) const;void socket::get_option(int level, int option, uint8&out value) const;void socket::get_option(int level, int option, timespan&out value) const;void socket::get_option(int level, int option, spec::ip_address&out value);
Arguments:
- int level: the protocol level of the option.
- int option: the option to get, as defined by the operating system.
- int&out value: receives the value of the option.
Remarks:
An exception is thrown if the option can't be read.
init
Create the underlying operating system socket for an address family, if it doesn't exist yet.
void socket::init(int af);
Arguments:
- int af: the address family, such as spec::IP_FAMILY_IPV4 or spec::IP_FAMILY_IPV6.
Remarks:
This is only needed to set options on a socket before it is connected, as connecting creates the socket otherwise.
poll
Wait until the socket is ready for reading or writing, or has an error.
bool socket::poll(const timespan&inout timeout, int mode) const;
Arguments:
- const timespan&inout timeout: the longest time to wait. timespan values are in microseconds, so
timespan(0)checks without waiting. - int mode: what to wait for, any combination of the socket_select_mode values combined with |.
Returns:
bool: true if the socket became ready for any of the modes within the timeout, false otherwise.
Remarks:
Polling with SOCKET_SELECT_READ and a timeout of 0 is a simple way to check whether data has arrived without blocking the game.
set_linger
Set whether closing the socket waits for unsent data to be delivered.
void socket::set_linger(bool on, int seconds);
Arguments:
- bool on: whether to linger when closing.
- int seconds: the longest time to linger for.
set_option
Set a socket option of the operating system's socket API.
void socket::set_option(int level, int option, int value);void socket::set_option(int level, int option, uint value);void socket::set_option(int level, int option, uint8 value);void socket::set_option(int level, int option, const timespan&in value);void socket::set_option(int level, int option, const spec::ip_address&in value);
Arguments:
- int level: the protocol level of the option, such as SOL_SOCKET (0xffff on Windows, 1 on Linux) or IPPROTO_TCP (6).
- int option: the option to set, as defined by the operating system.
- int value: the value of the option.
Remarks:
The common options have properties of their own, such as no_delay and keep_alive, which should be preferred as the numbers differ between operating systems. An exception is thrown if the option can't be set.
Properties
address
The local address and port of the socket.
const socket_address socket::address;
available
The number of bytes that can be read from the socket without blocking.
const int socket::available;
blocking
Whether the socket blocks until operations complete, which is the default.
bool socket::blocking;
Remarks:
A non-blocking socket returns straight away from sending and receiving even when nothing could be done, in which case an exception may be thrown or a negative value returned, so poll() should be used to find out when it is ready.
error
The pending error of the socket, as an operating system error code, or 0 if there isn't one.
const int socket::error;
Remarks:
Reading this clears the error.
is_datagram
Whether this is a datagram socket, such as a UDP socket.
const bool socket::is_datagram;
is_null
Whether the socket has no underlying operating system socket, such as before it is connected or after it has been assigned from a null socket.
const bool socket::is_null;
is_raw
Whether this is a raw socket.
const bool socket::is_raw;
is_stream
Whether this is a stream socket, such as a TCP connection.
const bool socket::is_stream;
keep_alive
Whether the operating system periodically checks that an idle connection is still alive (SO_KEEPALIVE).
bool socket::keep_alive;
no_delay
Whether Nagle's algorithm is disabled for the socket (TCP_NODELAY), so that small amounts of data are sent straight away rather than being collected into larger packets.
bool socket::no_delay;
Remarks:
Enabling this lowers latency, which suits games that send many small messages.
oob_inline
Whether out of band data is received along with the normal data (SO_OOBINLINE).
bool socket::oob_inline;
peer_address
The address and port of the other end of the socket's connection.
const socket_address socket::peer_address;
Remarks:
An exception is thrown if the socket isn't connected.
receive_buffer_size
The size in bytes of the operating system's receive buffer for the socket.
int socket::receive_buffer_size;
receive_timeout
How long receiving may block before an exception is thrown.
timespan socket::receive_timeout;
Remarks:
A timespan of 0, the default, means receiving blocks until data arrives.
reuse_address
Whether the socket can bind to an address that is still in use by a recently closed connection (SO_REUSEADDR).
bool socket::reuse_address;
reuse_port
Whether several sockets can bind to the same port (SO_REUSEPORT), on the systems that support it.
bool socket::reuse_port;
secure
Whether the socket uses TLS.
const bool socket::secure;
send_buffer_size
The size in bytes of the operating system's send buffer for the socket.
int socket::send_buffer_size;
send_timeout
How long sending may block before an exception is thrown.
timespan socket::send_timeout;
Remarks:
A timespan of 0, the default, means sending blocks for as long as it takes.
type
The type of the socket, a value of the socket_type enum.
const socket_type socket::type;
socket_address
An IP address and a port, which identify one end of a connection.
socket_address();
socket_address(spec::ip_address_family family);
socket_address(uint16 port);
socket_address(const spec::ip_address&in addr, uint16 port);
socket_address(const string&in host_and_port);
socket_address(const string&in host, uint16 port);
socket_address(spec::ip_address_family family, uint16 port);
socket_address(spec::ip_address_family family, const string&in addr);
socket_address(spec::ip_address_family family, const string&in host, uint16 port);
socket_address(spec::ip_address_family family, const string&in host, const string&in port);
socket_address(const socket_address&in other);
Arguments:
spec::ip_address_family family (2, 7, 8, 9, 10): the family of the address, a value of the spec::ip_address_family enum.
uint16 port (3, 4, 6, 7, 9, 10): the port. As a string, this can also be the name of a service such as
http.const spec::ip_address&in addr (4, 8): the IP address, either an ip_address or a string to parse.
const string&in host_and_port (5): an address and port together, such as
192.168.1.10:8080,[::1]:8080orlocalhost:8080.const string&in host (6, 9, 10): the host, either an IP address or a host name to resolve.
const socket_address&in other (11): an address to copy.
Remarks:
A socket_address is used to bind and connect sockets and is returned by them to say who they are connected to. Without an address it is the wildcard address of its family, and without a port it uses port 0, which lets the operating system pick one when binding.
Host names given to the constructors are resolved through DNS, which blocks until the lookup is done and throws an exception if it fails. A socket_address converts to its string form, such as 192.168.1.10:8080, implicitly, and addresses can be compared and sorted.
Example:
void main() {
socket_address server("127.0.0.1", 8080);
socket_address any_port(spec::IP_FAMILY_IPV6, 0);
alert("Socket addresses", "server: " + server + ", host " + server.host + ", port " + server.port + "\nIPv6 wildcard: " + any_port);
}
Properties
family
The family of the socket address, a value of the spec::ip_address_family enum.
const spec::ip_address_family socket_address::family;
host
The IP address of the socket address.
const spec::ip_address socket_address::host;
port
The port of the socket address.
const uint16 socket_address::port;
stream_socket
A TCP connection to a server, through which data can be sent and received in order.
stream_socket();
stream_socket(const socket&in sock);
stream_socket(const stream_socket&in sock);
stream_socket(const socket_address&in address);
stream_socket(const spec::ip_address_family family);
Arguments:
const socket&in sock (2, 3): a socket to share the underlying socket of, which must be a stream socket.
const socket_address&in address (4): an address and port to connect to straight away.
const spec::ip_address_family family (5): the address family of a socket created without connecting, so that options can be set before calling connect().
Remarks:
For networking between the players of a game, the network class is usually a better fit, as it handles connections, reliable and unreliable messages and channels for you.
A stream_socket has every method and property of socket, documented there, as well as the ones listed here. It connects to servers with connect(), or straight away when created with an address. NVGT doesn't provide server sockets that accept connections at this time.
Every method blocks until it completes unless the blocking property is set to false, so receiving in the game loop should be done after checking that data is available with poll() or the available property. An exception is thrown when connecting, sending or receiving fails.
Example:
void main() {
// Fetch a web page by speaking HTTP over a plain TCP connection.
stream_socket sock(socket_address("httpbin.org", 80));
sock.send_bytes("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n");
string response;
while (true) {
string data = sock.receive_bytes(4096, 0); // The flags must be given, as receive_bytes(4096) could also mean the other overload.
if (data.empty()) break; // The server closed the connection.
response += data;
}
sock.close();
alert("Response", response);
}
Methods
bind
Bind the socket to a local address and port, before connecting from it.
bool stream_socket::bind(const socket_address&in address, bool reuse_address = false, bool IPv6_only = false);
Arguments:
- const socket_address&in address: the local address and port to bind to.
- bool reuse_address = false: whether to allow binding to an address still in use by a recently closed connection.
- bool IPv6_only = false: for an IPv6 address, whether to refuse IPv4 connections mapped to IPv6.
Returns:
bool: true once the socket is bound. An exception is thrown if it can't be.
connect
Connect to a server, blocking until the connection is made.
void stream_socket::connect(const socket_address&in address);void stream_socket::connect(const socket_address&in address, const timespan&in timeout);
Arguments:
- const socket_address&in address: the address and port to connect to.
- const timespan&in timeout (2): the longest time to wait for the connection to be made.
Remarks:
An exception is thrown if the connection can't be made, such as when nothing is listening at the address or the timeout passes.
connect_nonblocking
Start connecting to a server without waiting for the connection to be made, making the socket non-blocking.
void stream_socket::connect_nonblocking(const socket_address&in address);
Arguments:
- const socket_address&in address: the address and port to connect to.
Remarks:
Use poll() with SOCKET_SELECT_WRITE to find out when the connection is made, after which the error property tells whether it succeeded.
receive_bytes
Receive data from the socket.
string stream_socket::receive_bytes(int length, int flags = 0);string stream_socket::receive_bytes(int flags = 0, const timespan&in timeout = 100000);
Arguments:
- int length (1): the most bytes to receive.
- int flags = 0: flags for the operating system's receive function, usually 0.
- const timespan&in timeout = 100000 (2): the longest time to wait for data to arrive. timespan values are in microseconds, so the default is a tenth of a second.
Returns:
string: the data received, or an empty string if the other end has shut down the connection or, for the second overload, if nothing arrived within the timeout.
Remarks:
The first overload blocks until some data arrives, which may be less than length, unless the socket is non-blocking or has a receive_timeout, in which case an exception is thrown when nothing arrives in time. The second overload receives however much data is available, waiting at most timeout for some to arrive.
Data sent through a stream socket arrives in order but isn't divided into messages, so a single send may arrive across several receives or several sends in one. Games usually prefix each message with its length.
As both overloads can be called with a single int, receive_bytes(4096) is ambiguous and doesn't compile, so give the flags as well, as in receive_bytes(4096, 0).
send_bytes
Send data through the socket.
int stream_socket::send_bytes(const string&in data, int flags = 0);
Arguments:
- const string&in data: the data to send.
- int flags = 0: flags for the operating system's send function, usually 0.
Returns:
int: the number of bytes sent, which may be less than the length of the data, in which case the rest should be sent again.
Remarks:
This blocks until the data can be handed to the operating system, unless the socket is non-blocking. An exception is thrown if sending fails, such as when the connection was lost.
shutdown
Stop both sending and receiving on the connection, the orderly way of ending it before close().
int stream_socket::shutdown();
Returns:
int: 0, or for a non-blocking TLS connection, a negative value if the shutdown must be retried once the socket can be written to.
shutdown_receive
Stop receiving on the connection, while still being able to send.
void stream_socket::shutdown_receive();
shutdown_send
Stop sending on the connection, telling the other end that no more data is coming, while still being able to receive.
int stream_socket::shutdown_send();
Returns:
int: 0, or for a non-blocking TLS connection, a negative value if the shutdown must be retried once the socket can be written to.
uri
A uniform resource identifier such as a web address, which can be built from or split into its scheme, authority, path, query and fragment.
uri();
uri(const string&in uri);
uri(const string&in scheme, const string&in path_etc);
uri(const string&in scheme, const string&in authority, const string&in path_etc);
uri(const string&in scheme, const string&in authority, const string&in path, const string&in query);
uri(const string&in scheme, const string&in authority, const string&in path, const string&in query, const string&in fragment);
uri(const spec::uri&in base_uri, const string&in relative_uri);
uri(const spec::path&in path);
uri(const spec::uri&in other);
Arguments:
const string&in uri (2): a complete URI to parse, such as
https://nvgt.dev/docs/?search=sound#top.const string&in scheme (3, 4, 5, 6): the scheme, such as
httpsorftp, which is converted to lowercase.const string&in path_etc (3, 4): the path, query and fragment, such as
/docs/?search=sound#top.const string&in authority (4, 5, 6): the user info, host and port, such as
user@example.com:8080.const string&in path (5, 6): the path.
const string&in query (5, 6): the query, without the leading question mark.
const string&in fragment (6): the fragment, without the leading hash.
const spec::uri&in base_uri (7): an absolute URI to resolve relative_uri against.
const string&in relative_uri (7): a URI relative to base_uri, such as
../images/logo.png.const spec::path&in path (8): a path to create a
file://URI from, which is made absolute first.const spec::uri&in other (9): a URI to copy.
Remarks:
This class is in the spec namespace, so scripts write it as spec::uri unless they have a using namespace spec; statement.
Constructing or assigning a uri from a string parses it, and an exception is thrown if the string isn't a valid URI. A uri converts to its string form implicitly, so it can be passed anywhere a string is expected, and a string can be passed to a function that takes a uri, such as http::get(), without writing spec::uri at all.
The scheme is converted to lowercase, and percent encoded characters in every part but the query and fragment are decoded. The query and fragment are stored percent encoded, which is why they have both a decoded property and a raw one.
Comparing two uris with == compares their scheme, authority, path, query and fragment, and a uri can also be compared with a string, which is parsed first.
Example:
void main() {
spec::uri u("https://user@nvgt.dev:8080/docs/audio/?search=sound+pool&page=2#top");
string info = "scheme: " + u.scheme + "\nhost: " + u.host + "\nport: " + u.port + "\nuser info: " + u.user_info + "\npath: " + u.path + "\nquery: " + u.query + "\nfragment: " + u.fragment;
string[][]@ params = u.get_query_parameters();
for (uint i = 0; i < params.length(); i++) info += "\nparameter " + params[i][0] + " = " + params[i][1];
u.resolve("../manual/");
info += "\nresolved against ../manual/: " + u;
alert("URI", info);
}
Methods
add_query_parameter
Add a parameter to the query of the URI, percent encoding its name and value.
void uri::add_query_parameter(const string&in param, const string&in value = "");
Arguments:
- const string&in param: the name of the parameter, which must not be empty.
- const string&in value = "": the value of the parameter. If empty, the parameter is added as
name=.
Remarks:
Unlike setting the query property, this also encodes any & and = characters in the name and value, so they can contain anything.
clear
Clear every part of the URI.
void uri::clear();
get_path_segments
Get the parts of the path between its slashes.
array<string>@ uri::get_path_segments() const;
Returns:
array/docs/audio/sound.html gives docs, audio and sound.html.
get_query_parameters
Get the parameters of the query as names and values.
array<array<string>>@ uri::get_query_parameters(bool plus_as_space = true) const;
Arguments:
- bool plus_as_space = true: whether plus signs are decoded as spaces, as they are in the queries web forms submit.
Returns:
array<array
normalize
Remove the . and .. segments from the path, other than leading ones.
void uri::normalize();
Remarks:
If the first segment of a relative path contains a colon, such as a Windows drive letter, ./ is put in front of it as RFC 3986 requires.
resolve
Resolve a relative URI against this one, which should be absolute, replacing this URI with the result.
void uri::resolve(const string&in relative_uri);void uri::resolve(const spec::uri&in relative_uri);
Arguments:
- const string&in relative_uri: the URI to resolve, such as
../manual/or/downloads. An absolute URI simply replaces this one.
Remarks:
This follows the algorithm in section 5.2 of RFC 3986, the same one a web browser uses for the links on a page.
Properties
authority
The authority of the URI, its user info, host and port, such as user@nvgt.dev:8080.
string uri::authority;
Remarks:
When the port is the well known port of the scheme it is left out. Setting the authority parses it and sets user_info, host and port.
fragment
The decoded fragment of the URI, the part after the hash without it.
string uri::fragment;
host
The host of the URI, such as nvgt.dev or an IP address.
string uri::host;
is_empty
Whether the URI is empty.
const bool uri::is_empty;
is_relative
Whether the URI is a relative reference, which has no scheme.
const bool uri::is_relative;
Remarks:
Relative references such as ../images/logo.png are usually resolved against an absolute URI with resolve().
path
The decoded path of the URI, such as /docs/index.html.
string uri::path;
path_and_query
The encoded path and query of the URI together, such as /docs/?search=sound, which is what an http request asks a server for.
const string uri::path_and_query;
path_etc
The encoded path, query and fragment of the URI together, such as /docs/?search=sound#top.
string uri::path_etc;
Remarks:
This is everything after the authority, and setting it parses it and sets path, query and fragment.
port
The port of the URI.
uint16 uri::port;
Remarks:
If no port was specified, this is the well known port of the scheme if there is one, such as 80 for http and 443 for https, or 0 otherwise. Use specified_port to find out whether a port was given.
query
The decoded query of the URI, the part after the question mark without it.
string uri::query;
Remarks:
Decoding turns %26 back into &, so a parameter whose name or value contains an encoded ampersand becomes ambiguous. Use raw_query or get_query_parameters() in that case.
Setting the query percent encodes it, but leaves ampersands alone so that they still separate parameters, and encodes any percent encoding it already contains a second time. To set a query that is already encoded use raw_query, and to build one from names and values use add_query_parameter(), which encodes them properly.
raw_fragment
The fragment of the URI as written, which is usually percent encoded.
string uri::raw_fragment;
Remarks:
A raw fragment that is set must already be properly percent encoded.
raw_query
The query of the URI as written, which is usually percent encoded.
string uri::raw_query;
Remarks:
A raw query that is set must already be properly percent encoded.
scheme
The scheme of the URI, such as http, https or file.
string uri::scheme;
Remarks:
Setting the scheme converts it to lowercase.
specified_port
The port written in the URI, or 0 if there isn't one.
const uint16 uri::specified_port;
Remarks:
Unlike port, this doesn't fall back to the well known port of the scheme.
user_info
The user information of the URI, the part before an @ in the authority, such as user:password.
string uri::user_info;
web_socket
A WebSocket connection, which exchanges whole messages called frames with a server over HTTP or HTTPS.
web_socket(const socket&in sock);
web_socket(const web_socket&in sock);
web_socket(http_client&inout cs, http_request&inout request, http_response&inout response);
web_socket(http_client&inout cs, http_request&inout request, http_response&inout response, http_credentials&inout credentials);
Arguments:
const socket&in sock (1, 2): a socket to share the underlying socket of, which must be a web socket.
http_client&inout cs (3, 4): an http_client or https_client connected to the server's host.
http_request&inout request (3, 4): the request starting the connection, whose uri is the path of the WebSocket endpoint, such as
/chat. The headers WebSocket needs are added to it.http_response&inout response (3, 4): receives the server's response to the request.
http_credentials&inout credentials (4): credentials to authenticate with if the server asks for them.
Remarks:
WebSockets are used by many web services for real time communication, such as chat servers and game lobbies. Unlike a stream_socket, data is sent and received as frames that each arrive whole, and text and binary frames can be told apart.
A web_socket is created by giving it an http_client or https_client for the server, an http_request whose uri is the path of the endpoint, and an http_response to fill in. The connection is made straight away, and an exception is thrown if the server refuses it, in which case the response holds the server's answer. After that, the client is no longer needed.
A web_socket has every method and property of socket and the shutdown, shutdown_send, shutdown_receive, send_bytes and receive_bytes methods of stream_socket, but frames should be sent with send_frame() and received with receive_frame(). Pings from the server arrive as frames too, and should be answered with a pong containing the same data.
Example:
void main() {
https_client client("echo.websocket.org");
http_request req(HTTP_GET, "/", HTTP_1_1);
http_response resp;
web_socket ws(client, req, resp);
int flags;
string greeting = ws.receive_frame(flags); // This server greets every connection.
ws.send_frame("Hello from NVGT!");
string echo = ws.receive_frame(flags);
ws.shutdown(WS_NORMAL_CLOSE);
alert("Web socket", "The server said " + greeting + " and echoed " + echo);
}
Methods
receive_frame
Receive a frame.
string web_socket::receive_frame(int&out flags);
Arguments:
- int&out flags: receives the flags and opcode of the frame.
flags & WS_FRAME_OP_BITMASKis the opcode, one of the web_socket_frame_opcodes values.
Returns:
string: the payload of the frame. An empty payload with flags of 0 means the other end has closed the connection.
Remarks:
This blocks until a whole frame has arrived, unless the socket is non-blocking. An exception is thrown if a frame is malformed or larger than max_payload_size, after which the connection must be closed, or if the receive_timeout passes.
send_frame
Send data as a single frame.
int web_socket::send_frame(const string&in data, int flags = WS_FRAME_TEXT);
Arguments:
- const string&in data: the payload of the frame.
- int flags = WS_FRAME_TEXT: the kind of frame to send, usually WS_FRAME_TEXT or WS_FRAME_BINARY. Control frames are sent by combining WS_FRAME_FLAG_FIN with an opcode, such as
WS_FRAME_FLAG_FIN | WS_FRAME_OP_PONG.
Returns:
int: the number of bytes sent, or for a non-blocking socket, -1 if the frame couldn't be sent in full, in which case it must be sent again with the same arguments once the socket can be written to.
shutdown
Close the connection in an orderly way by sending a close frame to the other end.
int web_socket::shutdown();int web_socket::shutdown(uint16 status_code, const string&in status_message = "");
Arguments:
- uint16 status_code (2): the reason for closing, a value of the web_socket_status_codes enum.
- const string&in status_message = "" (2): a short explanation of the reason.
Returns:
int: the number of bytes sent, or for a non-blocking socket, a negative value if the shutdown must be retried once the socket can be written to.
Remarks:
Without arguments, the status is WS_NORMAL_CLOSE. The other end answers with a close frame of its own, which receive_frame() returns.
Properties
max_payload_size
The largest frame payload in bytes that receive_frame() accepts.
int web_socket::max_payload_size;
Remarks:
A larger frame throws an exception. This defaults to the largest value an int can hold, so setting it protects against a server sending enormous frames.
mode
Whether this end of the connection is the client or the server, a value of the web_socket_mode enum.
const web_socket_mode web_socket::mode;
Constants
Event Types
This is a list of all the constants supported as event types by NVGT's networking layer.
- event_none: no event.
- event_connect: a new user wants to connect.
- event_disconnect: a user wants to disconnect.
- event_receive: a user sent a packet.
HTTP
These string constants hold standard values used when building HTTP requests and responses with classes such as http_request and http_response.
Protocol versions
- HTTP_1_0:
HTTP/1.0. - HTTP_1_1:
HTTP/1.1. This is the default version of an http_request created with a method and URI.
Request methods
- HTTP_GET:
GET. - HTTP_POST:
POST. - HTTP_PUT:
PUT. - HTTP_DELETE:
DELETE. - HTTP_HEAD:
HEAD. - HTTP_OPTIONS:
OPTIONS. - HTTP_PATCH:
PATCH.
Message bodies
- HTTP_CHUNKED_TRANSFER_ENCODING:
chunked, the transfer encoding in which the body is sent in a series of chunks, so its length doesn't need to be known in advance. - HTTP_IDENTITY_TRANSFER_ENCODING:
identity, the transfer encoding in which the body is sent as is. - HTTP_UNKNOWN_CONTENT_LENGTH: -1. This is an int rather than a string, and is the value of a message's
content_lengthproperty when no length has been set. - HTTP_UNKNOWN_CONTENT_TYPE: an empty string, the value of a message's
content_typeproperty when no content type has been set.
Example
void main() {
http_request request(HTTP_POST, "/scores", HTTP_1_1);
alert("Method", request.method);
alert("Version", request.version);
alert("Content length is unknown", request.content_length == HTTP_UNKNOWN_CONTENT_LENGTH ? "yes" : "no");
}
Enums
ftp_file_type
The ways ftp_client transfers files.
- FTP_FILE_TYPE_TEXT: text, in which line endings may be converted between systems.
- FTP_FILE_TYPE_BINARY: binary, in which files are transferred exactly as they are. This is the default and what should be used for anything but plain text.
http_status
The status codes of HTTP responses, as returned by http::status_code and http_response::status. Codes in the 200s mean success, the 300s redirection, the 400s an error on the client's side and the 500s an error on the server's side.
- HTTP_ACCEPTED: 202, the request was accepted but hasn't been acted on yet.
- HTTP_ALREADY_REPORTED: 208, the members of a collection were already reported.
- HTTP_BAD_GATEWAY: 502, a server the request was passed on to responded badly.
- HTTP_BAD_REQUEST: 400, the request was malformed.
- HTTP_CONFLICT: 409, the request conflicts with the current state of the resource.
- HTTP_CONTINUE: 100, the client should continue sending the request.
- HTTP_CREATED: 201, the request succeeded and created something.
- HTTP_ENCHANCE_YOUR_CALM: 420, the client is being rate limited, from Twitter's old API.
- HTTP_EXPECTATION_FAILED: 417, the server can't meet the request's Expect header.
- HTTP_FAILED_DEPENDENCY: 424, the request failed because another one it depended on failed.
- HTTP_FORBIDDEN: 403, the server refuses the request.
- HTTP_FOUND: 302, the resource is temporarily at the URL in the Location header.
- HTTP_GATEWAY_TIMEOUT: 504, a server the request was passed on to didn't respond in time.
- HTTP_GONE: 410, the resource is gone for good.
- HTTP_IM_A_TEAPOT: 418, the server refuses to brew coffee because it is a teapot.
- HTTP_IM_USED: 226, the response is the result of manipulations applied to the resource.
- HTTP_INSUFFICIENT_STORAGE: 507, the server can't store what is needed to complete the request.
- HTTP_INTERNAL_SERVER_ERROR: 500, the server failed while handling the request.
- HTTP_LENGTH_REQUIRED: 411, the request needs a Content-Length header.
- HTTP_LOCKED: 423, the resource is locked.
- HTTP_LOOP_DETECTED: 508, the server found an infinite loop while processing the request.
- HTTP_METHOD_NOT_ALLOWED: 405, the method isn't allowed for the resource.
- HTTP_MISDIRECTED_REQUEST: 421, the request went to a server that can't respond to it.
- HTTP_MOVED_PERMANENTLY: 301, the resource has moved to the URL in the Location header for good.
- HTTP_MULTIPLE_CHOICES: 300, there are several resources the client could choose from.
- HTTP_MULTI_STATUS: 207, the body holds the statuses of several operations.
- HTTP_NETWORK_AUTHENTICATION_REQUIRED: 511, the client must authenticate to gain network access, such as on a hotel's wifi.
- HTTP_NONAUTHORITATIVE: 203, the response comes from a proxy rather than the server itself.
- HTTP_NOT_ACCEPTABLE: 406, the resource can't be provided in any of the forms the request accepts.
- HTTP_NOT_EXTENDED: 510, the request needs further extensions.
- HTTP_NOT_FOUND: 404, nothing was found at the URL.
- HTTP_NOT_IMPLEMENTED: 501, the server doesn't support what the request needs.
- HTTP_NOT_MODIFIED: 304, the resource hasn't changed since the version the client has.
- HTTP_NO_CONTENT: 204, the request succeeded and there is no body.
- HTTP_OK: 200, the request succeeded.
- HTTP_PARTIAL_CONTENT: 206, the body is the part of the resource asked for with a Range header.
- HTTP_PAYMENT_REQUIRED: 402, reserved for payment being required.
- HTTP_PERMANENT_REDIRECT: 308, the resource has moved to the URL in the Location header for good, and the same method should be used there.
- HTTP_PRECONDITION_FAILED: 412, a precondition in the request's headers wasn't met.
- HTTP_PRECONDITION_REQUIRED: 428, the request must be conditional.
- HTTP_PROCESSING: 102, the server is still working on the request.
- HTTP_PROXY_AUTHENTICATION_REQUIRED: 407, the request needs authentication with the proxy.
- HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: 416, the range asked for can't be provided.
- HTTP_REQUEST_ENTITY_TOO_LARGE: 413, the body of the request is too large.
- HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: 431, the request's headers are too large.
- HTTP_REQUEST_TIMEOUT: 408, the server gave up waiting for the request.
- HTTP_REQUEST_URI_TOO_LONG: 414, the URI of the request is too long.
- HTTP_RESET_CONTENT: 205, the request succeeded and the client should reset its form.
- HTTP_SEE_OTHER: 303, the response can be found at the URL in the Location header with a GET request.
- HTTP_SERVICE_UNAVAILABLE: 503, the server is temporarily unable to handle the request, such as when overloaded or down for maintenance.
- HTTP_SWITCHING_PROTOCOLS: 101, the server is switching to the protocol the client asked for, such as when starting a web socket.
- HTTP_TEMPORARY_REDIRECT: 307, the resource is temporarily at the URL in the Location header, and the same method should be used there.
- HTTP_TOO_EARLY: 425, the server won't process a request that might be replayed.
- HTTP_TOO_MANY_REQUESTS: 429, the client has sent too many requests and is being rate limited.
- HTTP_UNAUTHORIZED: 401, the request needs authentication.
- HTTP_UNAVAILABLE_FOR_LEGAL_REASONS: 451, the resource is unavailable for legal reasons.
- HTTP_UNPROCESSABLE_ENTITY: 422, the request was well formed but its content was invalid.
- HTTP_UNSUPPORTED_MEDIA_TYPE: 415, the server doesn't support the type of the request's body.
- HTTP_UPGRADE_REQUIRED: 426, the client must switch to another protocol.
- HTTP_USE_PROXY: 305, the resource must be accessed through a proxy.
- HTTP_VARIANT_ALSO_NEGOTIATES: 506, the server is misconfigured.
- HTTP_VERSION_NOT_SUPPORTED: 505, the server doesn't support the HTTP version of the request.
http_status_reason() gives the standard reason phrase for any of these.
ip_address_family
The families of IP addresses, in the spec namespace, so written as spec::IP_FAMILY_IPV4 and so on.
- IP_FAMILY_UNKNOWN: the family isn't known.
- IP_FAMILY_unix_local: a Unix domain socket address, a path on the local computer rather than an IP address. On platforms without Unix domain sockets this is the same as IP_FAMILY_UNKNOWN.
- IP_FAMILY_IPV4: an IPv4 address such as 192.168.1.10.
- IP_FAMILY_IPV6: an IPv6 address such as ::1.
mail_priority
The priorities of a mail_message, set with mail_message::set_priority().
- MAIL_PRIORITY_HIGHEST: 1, the highest priority.
- MAIL_PRIORITY_HIGH: 2, high priority.
- MAIL_PRIORITY_NORMAL: 3, normal priority, which messages have if none is set.
- MAIL_PRIORITY_LOW: 4, low priority.
- MAIL_PRIORITY_LOWEST: 5, the lowest priority.
mail_recipient_type
The kinds of recipients of a mail_message.
- RECIPIENT_TO: a primary recipient, listed in the To header.
- RECIPIENT_CC: a carbon copy recipient, listed in the Cc header.
- RECIPIENT_BCC: a blind carbon copy recipient, who receives the message without being listed to the others.
smtp_auth_method
The ways smtp_client::login() can authenticate with a server.
- SMTP_AUTH_NONE: don't authenticate.
- SMTP_AUTH_LOGIN: the LOGIN method, which sends the username and password base64 encoded. This is the default and is widely supported, but should only be used over an encrypted connection.
- SMTP_AUTH_PLAIN: the PLAIN method, which also sends the username and password, and should only be used over an encrypted connection.
- SMTP_AUTH_CRAM_MD5: the CRAM-MD5 challenge response method, which doesn't send the password itself.
- SMTP_AUTH_CRAM_SHA1: the CRAM-SHA1 challenge response method.
- SMTP_AUTH_XOAUTH2: OAuth2, with an access token in place of the password. smtp_client::login_oauth2() uses this.
- SMTP_AUTH_NTLM: NTLM, used by some Microsoft servers.
socket_select_mode
What socket::poll() waits for, which can be combined with |.
- SOCKET_SELECT_READ: data can be read, or the connection was closed.
- SOCKET_SELECT_WRITE: data can be written, or a non-blocking connection has been made.
- SOCKET_SELECT_ERROR: an error occurred.
socket_type
The types of sockets, returned by socket::type.
- SOCKET_TYPE_STREAM: a stream socket, such as a TCP connection.
- SOCKET_TYPE_DATAGRAM: a datagram socket, such as a UDP socket.
- SOCKET_TYPE_RAW: a raw socket.
web_socket_error_codes
The reasons a web socket connection can fail, as reported in the messages of the exceptions thrown.
- WS_ERR_NO_HANDSHAKE: the server didn't respond with a WebSocket handshake.
- WS_ERR_HANDSHAKE_NO_VERSION: the handshake had no WebSocket version.
- WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION: the handshake had an unsupported WebSocket version.
- WS_ERR_HANDSHAKE_NO_KEY: the handshake had no key.
- WS_ERR_HANDSHAKE_ACCEPT: the server's handshake didn't accept the key.
- WS_ERR_UNAUTHORIZED: the server needs authentication.
- WS_ERR_PAYLOAD_TOO_BIG: a frame was larger than max_payload_size.
- WS_ERR_INCOMPLETE_FRAME: a frame was cut short.
web_socket_frame_flags
Flags of a web socket frame, combined with an opcode in the flags of web_socket::send_frame() and web_socket::receive_frame().
- WS_FRAME_FLAG_FIN: the frame is the final fragment of a message. Frames sent by send_frame() always are.
web_socket_frame_opcodes
The kinds of web socket frames, found in the flags returned by web_socket::receive_frame() with flags & WS_FRAME_OP_BITMASK.
- WS_FRAME_OP_CONT: a continuation of a fragmented message.
- WS_FRAME_OP_TEXT: a text frame, holding UTF-8 text.
- WS_FRAME_OP_BINARY: a binary frame.
- WS_FRAME_OP_CLOSE: a close frame, after which the connection ends.
- WS_FRAME_OP_PING: a ping, which should be answered with a pong holding the same data.
- WS_FRAME_OP_PONG: a pong, the answer to a ping.
- WS_FRAME_OP_BITMASK: the bits of the flags holding the opcode.
- WS_FRAME_OP_SETRAW: send the flags as given, for advanced uses such as fragmenting messages.
web_socket_mode
Which end of a connection a web_socket is, returned by web_socket::mode.
- WS_SERVER: the server end.
- WS_CLIENT: the client end.
web_socket_send_flags
The usual flags for web_socket::send_frame().
- WS_FRAME_TEXT: send a complete text frame, the default.
- WS_FRAME_BINARY: send a complete binary frame.
web_socket_status_codes
The reasons for closing a web socket connection, passed to web_socket::shutdown().
- WS_NORMAL_CLOSE: 1000, the connection is done with.
- WS_ENDPOINT_GOING_AWAY: 1001, this end is going away, such as a server shutting down.
- WS_PROTOCOL_ERROR: 1002, the other end broke the WebSocket protocol.
- WS_PAYLOAD_NOT_ACCEPTABLE: 1003, a frame held a kind of data that can't be accepted.
- WS_RESERVED: 1004, reserved.
- WS_RESERVED_NO_STATUS_CODE: 1005, reserved to report that no status was given, never sent.
- WS_RESERVED_ABNORMAL_CLOSE: 1006, reserved to report that the connection closed without a close frame, never sent.
- WS_MALFORMED_PAYLOAD: 1007, a frame held data inconsistent with its type, such as invalid UTF-8 in a text frame.
- WS_POLICY_VIOLATION: 1008, a frame broke this end's policy.
- WS_PAYLOAD_TOO_BIG: 1009, a frame was too large to process.
- WS_EXTENSION_REQUIRED: 1010, the server didn't agree to an extension the client needs.
- WS_UNEXPECTED_CONDITION: 1011, the server hit an unexpected problem.
- WS_RESERVED_TLS_FAILURE: 1015, reserved to report a failed TLS handshake, never sent.
Functions
broadcast_ip_address
Get the IPv4 broadcast address.
ip_address spec::broadcast_ip_address();
Returns:
ip_address: 255.255.255.255.
dns_resolve
Look up the name, aliases and addresses of a host.
dns_host_entry dns_resolve(const string&in address);
Arguments:
- const string&in address: a host name such as
nvgt.dev, or an IP address to look up the name of.
Returns:
dns_host_entry: the host's entry.
Remarks:
This blocks until the lookup completes and throws an exception if the host isn't found. See dns_host_entry for an example.
dns_resolve_single
Look up the first address of a host.
spec::ip_address dns_resolve_single(const string&in address);
Arguments:
- const string&in address: a host name such as
nvgt.dev, or an IP address.
Returns:
spec::ip_address: the first address the host resolved to.
Remarks:
This blocks until the lookup completes and throws an exception if the host isn't found.
html_entities_decode
Replace the HTML entities in a string, such as &, < or é, with the characters they stand for.
string html_entities_decode(const string&in input);
Arguments:
- const string&in input: the text to decode, such as text taken from a web page.
Returns:
string: the decoded text, in UTF-8.
http_credentials_extract
Split the user info of a URL into a username and password.
void http_credentials_extract(const string&in user_info, string&out username, string&out password);void http_credentials_extract(const spec::uri&in uri, string&out username, string&out password);
Arguments:
- const string&in user_info (1): user info such as
user:password. - string&out username: receives the username.
- string&out password: receives the password, or an empty string if there is none.
- const spec::uri&in uri (2): a URI whose user info to split.
http_credentials_is_basic
Find out whether an authentication header, or the Authorization header of a request, holds Basic credentials.
bool http_credentials_is_basic(const string&in header);bool http_credentials_is_basic(const http_request&in request);
Arguments:
- const string&in header (1): the value of a WWW-Authenticate or Authorization header.
- const http_request&in request (2): a request whose Authorization header to check.
Returns:
bool: true if the credentials use the Basic scheme.
http_credentials_is_digest
Find out whether an authentication header, or the Authorization header of a request, holds Digest credentials.
bool http_credentials_is_digest(const string&in header);bool http_credentials_is_digest(const http_request&in request);
Arguments:
- const string&in header (1): the value of a WWW-Authenticate or Authorization header.
- const http_request&in request (2): a request whose Authorization header to check.
Returns:
bool: true if the credentials use the Digest scheme.
http_credentials_is_ntlm
Find out whether an authentication header, or the Authorization header of a request, holds NTLM credentials.
bool http_credentials_is_ntlm(const string&in header);bool http_credentials_is_ntlm(const http_request&in request);
Arguments:
- const string&in header (1): the value of a WWW-Authenticate or Authorization header.
- const http_request&in request (2): a request whose Authorization header to check.
Returns:
bool: true if the credentials use the NTLM scheme.
http_credentials_is_proxy_basic
Find out whether a request's Proxy-Authorization header holds Basic credentials.
bool http_credentials_is_proxy_basic(const http_request&in request);
Arguments:
- const http_request&in request: the request to check.
Returns:
bool: true if the proxy credentials use the Basic scheme.
http_credentials_is_proxy_digest
Find out whether a request's Proxy-Authorization header holds Digest credentials.
bool http_credentials_is_proxy_digest(const http_request&in request);
Arguments:
- const http_request&in request: the request to check.
Returns:
bool: true if the proxy credentials use the Digest scheme.
http_credentials_is_proxy_ntlm
Find out whether a request's Proxy-Authorization header holds NTLM credentials.
bool http_credentials_is_proxy_ntlm(const http_request&in request);
Arguments:
- const http_request&in request: the request to check.
Returns:
bool: true if the proxy credentials use the NTLM scheme.
http_status_reason
Get the standard reason phrase of an HTTP status, such as Not Found for HTTP_NOT_FOUND.
string http_status_reason(http_status status);
Arguments:
- http_status status: the status, a value of the http_status enum.
Returns:
string: the reason phrase.
parse_email_message
Parse an email from its raw text, as stored in a .eml file.
mail_message@ parse_email_message(const string&in data);
Arguments:
- const string&in data: the raw text of the message, its headers followed by its content.
Returns:
mail_message@: a new mail_message with the sender, recipients, subject, content and threading headers of the email. If the email can't be parsed, the message is empty.
Remarks:
Only single part messages are fully supported at this time, attachments and alternative content aren't extracted.
parse_ip_address
Parse an IP address from a string without throwing an exception if it isn't valid.
bool spec::parse_ip_address(const string&in addr_in, ip_address&out addr_out);
Arguments:
const string&in addr_in: the address to parse, such as
192.168.1.10or::1.ip_address&out addr_out: the parsed address, if successful.
Returns:
bool: true if the string was a valid IP address, false otherwise.
Example:
void main() {
spec::ip_address addr;
string input = input_box("IP address", "Enter an IP address");
if (spec::parse_ip_address(input, addr)) alert("Valid", "The address " + addr + " is an IPv" + (addr.is_v4? "4" : "6") + " address.");
else alert("Invalid", input + " isn't an IP address.");
}
system_dns_host_entry
Get the name and addresses of the computer NVGT is running on.
dns_host_entry system_dns_host_entry();
Returns:
dns_host_entry: the entry of this computer.
url_decode
Decode a percent encoded string from a URL.
string url_decode(const string&in url, bool plus_as_space = true);
Arguments:
- const string&in url: the string to decode.
- bool plus_as_space = true: whether to decode plus signs as spaces, as web forms encode spaces in queries.
Returns:
string: the decoded string.
url_encode
Percent encode a string so it can be used in a URL, such as in a query parameter.
string url_encode(const string&in url, const string&in reserved = "");
Arguments:
- const string&in url: the string to encode.
- const string&in reserved = "": extra characters to encode, on top of the characters that are never allowed in a URL and those outside of ASCII.
Returns:
string: the encoded string.
Remarks:
Characters such as & and = are allowed in URLs, so to encode a value for a query, pass them as reserved, as in url_encode(value, "&=+#"). spec::uri::add_query_parameter() does this for you.
url_get
Make an HTTP GET request and wait for the response.
string url_get(const string&in url, http_response&out response = void);
Arguments:
const string&in url: the URL to request, with a scheme of http or https.
http_response&out response = void: if given, receives the status and headers of the response, or a status of 0 if no response arrived.
Returns:
string: the body of the response, or an empty string if the request failed.
Remarks:
This blocks the script until the request finishes, so it is best for small requests where waiting is acceptable. To keep the game running during a request, use the http class, which this function uses.
Example:
void main() {
http_response resp;
string version = url_get("https://nvgt.dev/downloads/latest_version", resp);
if (resp.status != HTTP_OK) alert("Error", "The request failed with status " + resp.status + ".");
else alert("Latest NVGT version", version);
}
url_post
Make an HTTP POST request and wait for the response.
string url_post(const string&in url, const string&in data, http_response&out response = void);
Arguments:
- const string&in url: the URL to post to, with a scheme of http or https.
- const string&in data: the body of the request. Unless the request says otherwise, servers take it to be form data, such as
name=Sam&score=1500. - http_response&out response = void: if given, receives the status and headers of the response, or a status of 0 if no response arrived.
Returns:
string: the body of the response, or an empty string if the request failed.
Remarks:
This blocks the script until the request finishes. To keep the game running during a request, use the http class, which this function uses. The request is sent with a Content-Type of application/x-www-form-urlencoded, url_encode() can encode the values in it.
url_request
Make an HTTP request with any method and wait for the response.
string url_request(const string&in method, const string&in url, const string&in data = "", http_response&out response = void);
Arguments:
- const string&in method: the method of the request, such as HTTP_PUT or HTTP_DELETE.
- const string&in url: the URL to request, with a scheme of http or https.
- const string&in data = "": the body of the request, if any.
- http_response&out response = void: if given, receives the status and headers of the response, or a status of 0 if no response arrived.
Returns:
string: the body of the response, or an empty string if the request failed.
Remarks:
This blocks the script until the request finishes. To keep the game running during a request, use the http class, which this function uses.
validate_email_address
Check whether a string looks like a valid email address.
bool validate_email_address(const string&in address);
Arguments:
- const string&in address: the address to check, such as
sam@example.com.
Returns:
bool: true if the address has a valid form, false otherwise.
Remarks:
This only checks the form of the address with a regular expression that accepts the common forms, it doesn't find out whether the address exists. Addresses with a name, such as Sam <sam@example.com>, aren't accepted.
wildcard_ip_address
Get the wildcard address of an address family, which a server binds to in order to listen on every network interface.
ip_address spec::wildcard_ip_address(ip_address_family family);
Arguments:
- ip_address_family family: the family of the address, a value of the spec::ip_address_family enum.
Returns:
ip_address: 0.0.0.0 for IPv4 or :: for IPv6.