xtd 0.2.0
Loading...
Searching...
No Matches
socket_tcp_ip_v6.cpp

Shows how to use xtd::net::sockets::socket class.

#include <xtd/net/sockets/socket>
#include <xtd/net/ip_end_point>
#include <xtd/threading/thread>
#include <xtd/console>
using namespace xtd;
using namespace xtd::net;
using namespace xtd::net::sockets;
using namespace xtd::threading;
auto main()->int {
auto terminate_app = false;
auto server = thread {[&] {
auto server_socket = socket {address_family::inter_network_v6, socket_type::stream, protocol_type::tcp};
server_socket.bind(ip_end_point {ip_address::ip_v6_any, 9400});
server_socket.listen();
auto new_socket = server_socket.accept();
while (!terminate_app) {
auto buffer = std::vector<unsigned char>(256);
auto number_of_byte_received = new_socket.receive(buffer);
if (number_of_byte_received) console::write_line(ustring(buffer.begin(), buffer.begin() + number_of_byte_received));
}
}};
auto client = thread {[&] {
auto client_socket = socket {address_family::inter_network_v6, socket_type::stream, protocol_type::tcp};
client_socket.connect(ip_address::ip_v6_loopback, 9400);
auto counter = 0;
while (!terminate_app) {
auto str = ustring::format("counter={}", ++counter);
client_socket.send(std::vector<unsigned char> {str.begin(), str.end()});
thread::sleep(50_ms);
}
}};
server.start();
client.start();
console::read_key();
terminate_app = true;
server.join();
client.join();
}
// This code produces the following output:
//
// counter=1
// counter=2
// counter=3
// counter=4
// counter=5
// ...
Represents a network endpoint as an IP address and a port number.
Definition ip_end_point.h:21
Implements the Berkeley sockets interface.
Definition socket.h:71
void bind(const end_point_t &local_end_point)
Associates a xtd::net::sockets::socket with a local endpoint.
Definition socket.h:795
void connect(const end_point_t &remote_end_point)
Establishes a connection to a remote host.
Definition socket.h:816
Creates and controls a thread, sets its priority, and gets its status.
Definition thread.h:41
Represents text as a sequence of UTF-8 code units.
Definition ustring.h:47
The xtd::net::sockets namespace provides a managed implementation of the Berkeley Sockets interface f...
Definition address_family.h:16
The xtd::net namespace provides a simple programming interface for many of the protocols used on netw...
Definition cookie_exception.h:10
The xtd::threading namespace provides classes and interfaces that enable multithreaded programming....
Definition abandoned_mutex_exception.h:10
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10