Skip to content

Networking

This section contains the references for communicating over networks and the internet.

Which part to use depends on what is being talked to:

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.

  1. dns_host_entry();

  2. dns_host_entry(const dns_host_entry&in other);

Arguments:

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@: the aliases of the host, which is often empty.

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.

  1. ftp_client(uint16 active_data_port = 0);

  2. ftp_client(const string&in host, uint16 port = 21, const string&in username = "", const string&in password = "", uint16 active_data_port = 0);

Arguments (1):

Arguments (2):

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:
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:
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:
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:
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:
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:
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:
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:
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:
send_command

Send a command to the server exactly as it is given and wait for the response.

  1. int ftp_client::send_command(const string&in command, string& response);
  2. int ftp_client::send_command(const string&in command, const string&in argument, string& response);
Arguments:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:

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:
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:
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:
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.

  1. http_credentials();

  2. http_credentials(const string&in username, const string&in password);

Arguments:

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:
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:
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:
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:
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:
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:

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.

  1. http_request();

  2. http_request(const http_request&in other);

  3. http_request(const string&in method, const string&in uri, const string&in version = HTTP_1_1);

  4. http_request(\{\{string, string}, ...});

Arguments:

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:
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:
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:
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:
set_credentials

Set the request's Authorization header.

void http_request::set_credentials(const string&in scheme, const string&in auth_info);

Arguments:
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:

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.

  1. http_response();

  2. http_response(const http_response&in other);

  3. http_response(http_status status);

  4. http_response(http_status status, const string&in reason);

  5. http_response(const string&in version, http_status status, const string&in reason);

  6. http_response(const string&in version, http_status status);

  7. http_response(\{\{string, string}, ...});

Arguments:

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.

  1. void http_response::set_status_and_reason(http_status status, const string&in reason);
  2. void http_response::set_status_and_reason(http_status status);
Arguments:

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:

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.

  1. internet_message_header();
  2. internet_message_header(const internet_message_header&in other);
  3. internet_message_header(\{\{string, string}, ...});

Arguments:

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:
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:
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:
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:
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.

  1. ip_address();

  2. ip_address(spec::ip_address_family family);

  3. ip_address(const string&in addr);

  4. ip_address(const string&in addr, spec::ip_address_family family);

  5. ip_address(const spec::ip_address&in other);

Arguments:

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.

  1. void ip_address::mask(const spec::ip_address&in mask);
  2. void ip_address::mask(const spec::ip_address&in mask, const spec::ip_address&in set);
Arguments:
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:
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:
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:
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:
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:
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.

  1. void mail_message::add_recipient(const mail_recipient&in recipient);
  2. void mail_message::add_recipient(const string&in address, mail_recipient_type type = RECIPIENT_TO);
Arguments:
get_header

Get a header of the message.

string mail_message::get_header(const string&in name) const;

Arguments:
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:
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:
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:
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:
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:
set_subject

Set the subject of the message.

void mail_message::set_subject(const string&in subject);

Arguments:

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.

  1. mail_recipient();
  2. mail_recipient(mail_recipient_type type, const string&in address, const string&in real_name = "");

Arguments:

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.

  1. name_value_collection();

  2. name_value_collection(const name_value_collection&in other);

  3. name_value_collection(\{\{string, string}, ...});

Arguments:

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:
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:
exists

Find out whether a name is in the collection.

bool name_value_collection::exists(const string&in name) const;

Arguments:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
setup_client

Sets up the network object as a client.

bool network::setup_client(uint8 max_channels, uint16 max_peers);

Arguments:
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:
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:
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:
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:
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:
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:
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.

  1. socket();
  2. socket(const socket&in sock);

Arguments:

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:
get_option

Get a socket option of the operating system's socket API.

  1. void socket::get_option(int level, int option, int&out value) const;
  2. void socket::get_option(int level, int option, uint&out value) const;
  3. void socket::get_option(int level, int option, uint8&out value) const;
  4. void socket::get_option(int level, int option, timespan&out value) const;
  5. void socket::get_option(int level, int option, spec::ip_address&out value);
Arguments:
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:
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:
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:
set_option

Set a socket option of the operating system's socket API.

  1. void socket::set_option(int level, int option, int value);
  2. void socket::set_option(int level, int option, uint value);
  3. void socket::set_option(int level, int option, uint8 value);
  4. void socket::set_option(int level, int option, const timespan&in value);
  5. void socket::set_option(int level, int option, const spec::ip_address&in value);
Arguments:
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.

  1. socket_address();

  2. socket_address(spec::ip_address_family family);

  3. socket_address(uint16 port);

  4. socket_address(const spec::ip_address&in addr, uint16 port);

  5. socket_address(const string&in host_and_port);

  6. socket_address(const string&in host, uint16 port);

  7. socket_address(spec::ip_address_family family, uint16 port);

  8. socket_address(spec::ip_address_family family, const string&in addr);

  9. socket_address(spec::ip_address_family family, const string&in host, uint16 port);

  10. socket_address(spec::ip_address_family family, const string&in host, const string&in port);

  11. socket_address(const socket_address&in other);

Arguments:

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.

  1. stream_socket();

  2. stream_socket(const socket&in sock);

  3. stream_socket(const stream_socket&in sock);

  4. stream_socket(const socket_address&in address);

  5. stream_socket(const spec::ip_address_family family);

Arguments:

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:
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.

  1. void stream_socket::connect(const socket_address&in address);
  2. void stream_socket::connect(const socket_address&in address, const timespan&in timeout);
Arguments:
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:
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.

  1. string stream_socket::receive_bytes(int length, int flags = 0);
  2. string stream_socket::receive_bytes(int flags = 0, const timespan&in timeout = 100000);
Arguments:
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:
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.

  1. uri();

  2. uri(const string&in uri);

  3. uri(const string&in scheme, const string&in path_etc);

  4. uri(const string&in scheme, const string&in authority, const string&in path_etc);

  5. uri(const string&in scheme, const string&in authority, const string&in path, const string&in query);

  6. uri(const string&in scheme, const string&in authority, const string&in path, const string&in query, const string&in fragment);

  7. uri(const spec::uri&in base_uri, const string&in relative_uri);

  8. uri(const spec::path&in path);

  9. uri(const spec::uri&in other);

Arguments:

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:
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@: the segments of the path, so /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:
Returns:

array<array>@: a list of parameters in the order they appear, each an array holding the name and then the value, both decoded.

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.

  1. void uri::resolve(const string&in relative_uri);
  2. void uri::resolve(const spec::uri&in relative_uri);
Arguments:
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.

  1. web_socket(const socket&in sock);

  2. web_socket(const web_socket&in sock);

  3. web_socket(http_client&inout cs, http_request&inout request, http_response&inout response);

  4. web_socket(http_client&inout cs, http_request&inout request, http_response&inout response, http_credentials&inout credentials);

Arguments:

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:
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:
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.

  1. int web_socket::shutdown();
  2. int web_socket::shutdown(uint16 status_code, const string&in status_message = "");
Arguments:
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.

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

Request methods

Message bodies

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.

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_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.

mail_priority

The priorities of a mail_message, set with mail_message::set_priority().

mail_recipient_type

The kinds of recipients of a mail_message.

smtp_auth_method

The ways smtp_client::login() can authenticate with a server.

socket_select_mode

What socket::poll() waits for, which can be combined with |.

socket_type

The types of sockets, returned by socket::type.

web_socket_error_codes

The reasons a web socket connection can fail, as reported in the messages of the exceptions thrown.

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().

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.

web_socket_mode

Which end of a connection a web_socket is, returned by web_socket::mode.

web_socket_send_flags

The usual flags for web_socket::send_frame().

web_socket_status_codes

The reasons for closing a web socket connection, passed to web_socket::shutdown().

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:

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:

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 &amp;, &lt; or &#233;, with the characters they stand for.

string html_entities_decode(const string&in input);

Arguments:

Returns:

string: the decoded text, in UTF-8.

http_credentials_extract

Split the user info of a URL into a username and password.

  1. void http_credentials_extract(const string&in user_info, string&out username, string&out password);
  2. void http_credentials_extract(const spec::uri&in uri, string&out username, string&out password);

Arguments:

http_credentials_is_basic

Find out whether an authentication header, or the Authorization header of a request, holds Basic credentials.

  1. bool http_credentials_is_basic(const string&in header);
  2. bool http_credentials_is_basic(const http_request&in request);

Arguments:

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.

  1. bool http_credentials_is_digest(const string&in header);
  2. bool http_credentials_is_digest(const http_request&in request);

Arguments:

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.

  1. bool http_credentials_is_ntlm(const string&in header);
  2. bool http_credentials_is_ntlm(const http_request&in request);

Arguments:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

Returns:

ip_address: 0.0.0.0 for IPv4 or :: for IPv6.