Babel  1
The voip software that only works on your local network
Loading...
Searching...
No Matches
TCP.cpp
Go to the documentation of this file.
1
7#include "Network/TCP.hpp"
8
9namespace Network
10{
19 TCP::TCP(asio::io_context &io_context, const std::string &ip, int port, bool is_sender)
20 : _io_context(io_context), _socket(io_context), _acceptor(io_context), _is_sender(is_sender)
21 {
22 if (is_sender) {
23 // Client (Sender Mode) connects
24 asio::ip::tcp::endpoint endpoint(asio::ip::make_address(ip), port);
25 _socket.connect(endpoint);
26 startRead(); // Start reading responses from the receiver
27 } else {
28 // Server (Receiver Mode)
29 asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
30 _acceptor.open(asio::ip::tcp::v4());
31 _acceptor.set_option(asio::socket_base::reuse_address(true));
32 _acceptor.bind(endpoint);
33 _acceptor.listen();
34
35 // Accept connections in a separate thread
36 _server_thread = std::make_shared<std::thread>([this]() { startAccept(); });
37 }
38 }
39
44 {
45 if (!_is_sender && _server_thread && _server_thread->joinable()) {
46 _server_thread->join();
47 }
48 _socket.close();
49 _acceptor.close();
50 }
51
57 void TCP::sendTo(const std::string &message)
58 {
59 if (_socket.is_open()) {
60 asio::write(_socket, asio::buffer(message));
61 }
62 }
63
67 void TCP::startAccept()
68 {
69 _acceptor.async_accept([this](std::error_code ec, asio::ip::tcp::socket new_socket)
70 {
71 if (!ec) {
72 _socket = std::move(new_socket);
73 startRead(); // Start reading messages after connection is established
74 }
75 });
76
77 _io_context.run();
78 }
79
83 void TCP::startRead()
84 {
85 auto buffer = std::make_shared<std::vector<char>>(1024);
86 _socket.async_read_some(asio::buffer(*buffer),
87 [this, buffer](std::error_code ec, std::size_t length)
88 {
89 if (!ec) {
90 _received_packets.push(std::string(buffer->data(), length));
91 startRead(); // Continue reading more messages
92 }
93 }
94 );
95 }
96
102 std::string TCP::receive()
103 {
104 if (_received_packets.empty()) {
105 return "";
106 }
107 std::string packet = _received_packets.front();
108 _received_packets.pop();
109 return packet;
110 }
111
118 {
119 return _socket.is_open();
120 }
121
127 std::string TCP::fetchPacket()
128 {
129 return receive();
130 }
131}
This file contains the definition of the TCP class for handling TCP network communication.
~TCP()
Destroy the TCP object.
Definition TCP.cpp:43
TCP(asio::io_context &io_context, const std::string &ip, int port, bool is_sender)
Construct a new TCP object.
Definition TCP.cpp:19
std::string fetchPacket()
Fetch a packet from the received packets queue.
Definition TCP.cpp:127
bool isConnectionAlive()
Check if the connection is alive.
Definition TCP.cpp:117
void sendTo(const std::string &message)
Send a message to the connected peer.
Definition TCP.cpp:57
std::string receive()
Receive a message from the connected peer.
Definition TCP.cpp:102