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

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

#include <xtd/io/stream_reader>
#include <xtd/io/stream_writer>
#include <xtd/net/sockets/socket>
#include <xtd/net/sockets/network_stream>
#include <xtd/net/ip_end_point>
#include <xtd/threading/thread>
#include <xtd/console>
using namespace xtd;
using namespace xtd::io;
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, socket_type::stream, protocol_type::tcp};
server_socket.bind(ip_end_point {ip_address::any, 9400});
server_socket.listen();
auto stream = network_stream {server_socket.accept()};
auto reader = stream_reader {stream};
while (!terminate_app)
if (stream.data_available()) console::write_line(reader.read_line());
}};
server.start();
auto client = thread {[&] {
auto stream = network_stream {socket {address_family::inter_network, socket_type::stream, protocol_type::tcp}};
stream.socket().connect(ip_address::loopback, 9400);
auto writer = stream_writer {stream};
auto counter = 0;
while (!terminate_app) {
writer.write_line(string::format("counter={}", ++counter));
thread::sleep(50_ms);
}
}};
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
// ...
Implements a xtd::io::text_reader that reads characters from a byte stream.
Definition stream_reader.hpp:28
Implements a xtd::io::text_writer for writing characters to a stream.
Definition stream_writer.hpp:28
Represents a network endpoint as an IP address and a port number.
Definition ip_end_point.hpp:23
Provides the underlying stream of data for network access.
Definition network_stream.hpp:37
Implements the Berkeley sockets interface.
Definition socket.hpp:74
void bind(const end_point_t &local_end_point)
Associates a xtd::net::sockets::socket with a local endpoint.
Definition socket.hpp:798
Creates and controls a thread, sets its priority, and gets its status.
Definition thread.hpp:43
The xtd::io namespace contains types that allow reading and writing to files and data streams,...
Definition binary_reader.hpp:16
The xtd::net::sockets namespace provides a managed implementation of the Berkeley Sockets interface f...
Definition address_family.hpp:16
The xtd::net namespace provides a simple programming interface for many of the protocols used on netw...
Definition cookie_exception.hpp:11
The xtd::threading namespace provides classes and interfaces that enable multithreaded programming....
Definition abandoned_mutex_exception.hpp:11
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.hpp:10