Chapter 10: Clients
This chapter describes the calling models of the HTTP, WebSocket, TCP, and UDP clients and their thread boundary with a server Reactor.
1. Client execution models
| Client | Model |
|---|---|
| TcpClient | Blocking by default; finite connect, read, and write timeouts bound each operation. |
| HttpClient | Synchronous request; a successful send only writes the request; isReturn() indicates whether a valid response arrived. |
| WebSocketClient | Uses an internal listening thread and asynchronous message callback. |
| UdpClient | Direct datagram send/receive in blocking or non-blocking mode. |
A blocking HttpClient/TcpClient call pauses the Server Reactor. WorkerPool provides the execution boundary for external calls, with finite timeouts on the underlying client operations.
2. HTTP client demo
#include <sttnet.h>
#include <iostream>
int main()
{
using stt::network::HttpClient;
// HttpClient is a synchronous client. Use a finite timeout in production
// and run it outside an STTNet Reactor callback.
HttpClient client;
if(!client.getRequest("http://127.0.0.1:8080/ping", "",
"Connection: close", 5))
{
std::cerr << "request could not be sent\n";
return 1;
}
// Sending successfully is not the same as receiving a complete response.
if(!client.isReturn())
{
std::cerr << "server did not return a complete HTTP response\n";
return 2;
}
std::cout << "--- response headers ---\n" << client.header
<< "\n--- response body ---\n" << client.body << '\n';
return 0;
}./build/examples/sttnet_http_hello
# Another terminal:
./build/examples/sttnet_http_client3. WebSocket client demo
#include <sttnet.h>
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
using stt::network::WebSocketClient;
WebSocketClient client;
// The callback runs on the client's internal listening thread.
client.setFunction(
[](const std::string &message, WebSocketClient &) {
std::cout << "received: " << message << '\n';
return true; // false closes the WebSocket connection.
});
if(!client.connect("ws://127.0.0.1:5050/echo"))
{
std::cerr << "WebSocket connection failed\n";
return 1;
}
if(!client.sendMessage("hello from STTNet client"))
{
std::cerr << "send failed\n";
client.close(1011, "send failed");
return 2;
}
// Give the asynchronous receive callback time to print the echo.
std::this_thread::sleep_for(std::chrono::seconds(1));
client.close(1000, "demo complete");
return 0;
}./build/examples/sttnet_websocket_echo
# Another terminal:
./build/examples/sttnet_websocket_client4. Complete URLs
Client URLs contain the protocol, port, and path, for example https://example.com:443/ or ws://127.0.0.1:5050/echo. TLS clients validate both the certificate chain and target hostname.