boost::asio server with simple functions - c++

Guys I really need your help. I'm learning boost::asio and I have 2 problems that I can't deal for days...
Here is an example of a simple echo server done by myself:
int main(
{
// crate a server, binding it and listening connections
// acceptor server;
//socket client
server.async_accept(client, boost::bind(accept_handle, _1, &server, &client));
io_service.run();
return 0;
}
void accept_handle(const boost::system::error_code& eCode, boost::asio::ip::tcp::acceptor* server, boost::asio::ip::tcp::socket* client)
{
char data[43];
client->async_read_some(boost::asio::buffer(data, 20), boost::bind(read_handle, _1, _2, server, client));
}
void read_handle(const boost::system::error_code& eCode, size_t bytes)
{
char data_buf[20] = "hello";
client->async_write_some(boost::buufer(data, 5), boost::bind(write_handle, _1, _2, server, client));
}
void write_accept(const boost::system::error_code& eCode, size_t bytes)
{
boost::asio::ip::tcp::socket newConnection(server->get_ioservice)); // taking he io_service of the server
server->async_accept(newConnection, boost::bind(accept_handle, _1, server, client));
}
The problem is the server accept one client and it does not accept other pending client.. where am i doing wrong here
NOTE: I wrote this code in notepad so sorry for syntax errors if there are any.
Thanks for your help in advance!!!

The code can only accept one connection because it is not calling async_accept in the accept_handle function.
The code may also have a problem with object lifetimes: it would be wise to use shared pointers to manage the clients see: Boost async_* functions and shared_ptr's.

Related

boost asio broadcast not going out on all interfaces

If set up a program with boost asio.
Broadcasts are working fine, if only one network interface is present.
However, if there are more network interfaces each broadcast is being sent on one interface only. The interface changes randomly. As observed by wireshark.
I'd expect each broadcast to go out on every interface.
Who's wrong? Me, boost or my understanding of how to use boost. Well, I'm aware, that the latter is the most probable :).
And how can I get the expected behavior.
int myPort=5000;
boost::asio::io_context io_Context{};
boost::asio::ip::udp::socket socket{io_Context};
std::thread sendWorkerThread;
void SendWorkerStart() {
boost::asio::executor_work_guard<decltype(io_Context.get_executor())> work { io_Context.get_executor() };
io_Context.run();
}
void setupSocket() {
socket.set_option(boost::asio::socket_base::reuse_address(true));
socket.set_option(boost::asio::socket_base::broadcast(true));
boost::system::error_code ec;
socket.bind(boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::any(), myPort), ec);
sendWorkerThread = std::thread(udpSocket_c::SendWorkerStart, this);
SendWorkerStart();
}
void SendBroadcast(UdpMessage_t &&message, int size) {
boost::system::error_code ec;
std::lock_guard<std::mutex> lockGuard(sendMutex);
udp::endpoint senderEndpoint(boost::asio::ip::address_v4::broadcast(), myPort);
socket.async_send_to(boost::asio::buffer(message->data(), size), senderEndpoint,
[this](const boost::system::error_code& error,
std::size_t bytes_transferred) { /* nothing to do */} );
}
Thanks for your help.
Edit: It's now running on Windows, but needs to work also in Linux.
As suggested by Alan Birtles in the comments to the question i found an explanation here:
UDP-Broadcast on all interfaces
I solved the issue by iterating over he configured interfaces and sending the broadcast to each networks broadcast address as suggested by the linked answer.

How to make a multi-client server with synchronous dataread/write functions?

Okay, so I might have got myself a big problem here. All this time, I've been basing my code in something I might not have wanted, that is, I'm using synchronous boost::asio functions with a server that can have multiple clients at the same time. Here it is:
void session(tcp::socket socket, std::vector<Player>* pl)
{
debug("New connection! Reading username...\n");
/* ...Username verification code removed... */
debug("Client logged in safely as ");
debug(u->name);
debug("\n");
for (;;)
{
boost::array<unsigned char, 128> buf;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
{
debug("Connection ended.\n");
break; // Connection closed cleanly by peer.
}
else if (error)
throw boost::system::system_error(error); // Some other error.
DataHeader ins = static_cast<DataHeader>(buf.data()[0]);
std::vector<unsigned char> response;
/* ... Get appropiate response... */
// send response
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(response), ignored_error);
//debug("Sent ");
//debug(response.size());
//debug("B to client.\n");
}
}
As you can see from the code, I'm using read_some and write functions in a non-ideal scenario. Now, the question is, how did I make this code usable for multiple clients at the same time? Well, I used threads:
int main()
{
try
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 13));
debug("Ready.\n");
for (;;)
{
std::thread(session, acceptor.accept(), &players).detach(); // Accept incoming clients
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
Now, I've never had a problem with this setup until recently, that I started testing multiple clients at the same time on one server. This made the server crash many times, and just until now, I thought the problem were just connection issues. However, now I've started to wonder, "Might the problem be the synchronous functions?"
All the examples I've seen until now of multi-client servers use async functions, and maybe it's because they are needed. So, my final question is, do I really need async functions? Is there anything wrong with this code to make it crash? And finally, if async functions are needed, how could I implement them? Many thanks in advance!
As user VTT has pointed out, although this approach may work for a little bit, it's just better to switch to async functions due to resource exhaustion, so, I'll just redo the entire server to implement them.

Server and Client at same time with Boost-Asio

I am an AspNet programmer with 57 years of age. Because I was the only one who worked a little, back in the beginning, with C ++, my bosses asked me to serve a customer who needs a communication agent with very specific characteristics. It can run as a daemon on multiple platforms and be both client and server at times. I do not know enough but I have to solve the problem and found a chance in the Boost / Asio library.
I am new to Boost-Asio and reading the documentation I created a server and a TCP socket client that exchanges messages perfectly and two-way, full duplex.
I read several posts where they asked for the same things I want, but all the answers suggested full duplex as if that meant having a client and a server in the same program. And it's not. The definition of full duplex refers to the ability to write and read from the same connection and every TCP connection is full duplex by default.
I need to make two programs can accept connections initiated by the other. There will be no permanent connection between the two programs. Sometimes one of them will ask for a connection and at other times the other will make this request and both need to be listening, accepting the connection, exchanging some messages and terminating the connection until new request is made.
The server I did seems to get stuck in the process of listening to the port to see if a connection is coming in and I can not continue with the process to be able to create a socket and request a connection with the other program. I need threads but I do not know enough about them.
It'is possible?
As I said I'm new to Boost / Asio and I tried to follow some documents of threads and Coroutines. Then I put the client codes in one method and the server in another.:
int main(int argc, char* argv[])
{
try
{
boost::thread t1(&server_agent);
boost::thread t2(&client_agent);
// wait
t1.join();
t2.join();
return 0;
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
and two Coroutines:
void client_agent() {
parameters param;
param.load();
boost::asio::io_service io_service1;
tcp::resolver resolver(io_service1);
char port[5];
_itoa(param.getNrPortaServComunic(), port, 10);
auto endpoint_iterator = resolver.resolve({ param.getIPServComunicPrincipal(), port });
std::list<client> clients;
client c(io_service1, endpoint_iterator, param);
while (true)
{
BOOL enviada = FALSE;
while (true) {
if (!enviada) {
std::cout << "sending a message\n";
int nr = 110;
message msg(nr, param);
c.write(msg);
enviada = TRUE;
}
}
}
c.close();
}
void server_agent() {
parameters param;
param.load();
boost::asio::io_service io_service1;
std::list<server> servers;
tcp::endpoint endpoint(tcp::v4(), param.getNrPortaAgenteServ());
servers.emplace_back(io_service1, endpoint);
io_service1.run();
}
I used one port to client endpoint and other port to server endpoint. Is it correct? Required?
It starts looking like it's going to work. Each of the methods runs concurrently but then I get a thread allocation error at the io_service1.run (last line of the server_agent method):
boost::exception_detail::clone_impl > at memory location 0x0118C61C.
Any suggestion?
You are describing a UDP client/server application. But your implementation is bound to fail. Think of an asio server or client as always running in a single thread.
The following code is just so you get an idea. I haven't tried to compile it. Client is very similar, but may need a transmit buffer, depends on the app, obviously.
This is a shortened version, so you get the idea. In a final application you way want to add receive timeouts and the likes. The same principles hold for TCP servers, with the added async_listen call. Connected sockets can be stored in shared_ptr, and captured by the lambdas, will destroy almost magically.
Server is basically the same, except there is no constant reading going on. If running both server and client in the same process, you can rely on run() to be looping because of the server, but if not, you'd have to call run() for each connection. run() would exit at the end of the exchange.
using namespace boost::asio; // Or whichever way you like to shorten names
class Server
{
public:
Server(io_service& ios) : ios_(ios) {}
void Start()
{
// create socket
// Start listening
Read();
}
void Read()
{
rxBuffer.resize(1024)
s_.async_receive_from(
buffer(rxBuffer),
remoteEndpoint_,
[this](error_code ec, size_t n)
{
OnReceive(ec, n); // could be virtual, if done this way
});
}
void OnReceive(error_code ec, size_t n)
{
rxBuffer_.resize(n);
if (ec)
{
// error ... stops listen loop
return;
}
// grab data, put in txBuffer_
Read();
s_.async_send_to(
buffer(txBuffer_),
remoteEndpoint_,
[this, msg](error_code ec, size_t n)
{
OnTransmitDone(ec, n);
});
}
void OnTransmitDone(error_code ec, size_t n)
{
// check for error?
txBuffer_.clear();
}
protected:
io_service& ios_;
ip::udp::socket s_;
ip::udp::endpoint remoteEndpoint_; // the other's address/port
std::vector<char> rxBuffer_; // could be any data type you like
std::vector<char> txBuffer_; // idem All access is in one thread, so only
// one needed for simple ask/respond ops.
};
int main()
{
io_service ios;
Server server(ios); // could have both server and client run on same thread
// on same io service this way.
Server.Start();
ios_run();
// or std::thread ioThread([&](){ ios_.run(); });
return 0;
}

Operation canceled boost asio async_receive_from

I have an UDP Server set up with boost/asio (I copied the example and just changed a few things). Below is the code:
udp_server.hpp
using boost::asio::ip::udp;
class udp_server {
public:
udp_server(boost::asio::io_service&, int);
private:
boost::array<char, 256> recBuffer;
udp::socket socket_;
udp::endpoint remote_endpoint_;
void start_receive();
void handle_receive(const boost::system::error_code&, std::size_t);
void handle_send(boost::shared_ptr<std::string> /*message*/,
const boost::system::error_code& /*error*/,
std::size_t /*bytes_transferred*/)
{}
};
and udp_server.cpp
udp_server::udp_server( boost::asio::io_service& io_service,
int port)
: socket_(io_service, udp::endpoint(udp::v4(), port)) {
serverNotifications.push_back("UDP Server class initialized.");
start_receive();
}
void udp_server::start_receive() {
socket_.async_receive_from(
boost::asio::buffer(recBuffer),
remote_endpoint_,
boost::bind(&udp_server::handle_receive,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
serverNotifications.push_back("Starting to receive UDP Messages.");
}
void udp_server::handle_receive(const boost::system::error_code& error,
std::size_t size) {
serverNotifications.push_back("RecFrom: " + remote_endpoint_.address().to_string());
if (!error) {
// I do data stuff here
} else {
errors.push_back("Handle Receive error: " + error.message());
}
}
After initializing the Server with:
try {
udp_server server(io_service, ApplData.PORT, (size_t)ApplData.BUFLEN);
} catch (std::exception& e) {
// error handling
}
and running it with io_service.run() in a seperate try catch in another function I get some problems:
My Callback function handle_receive gets called without any UDP message getting send in the whole network (aka only my laptop without connection)
error.message() returns "Operation canceled"
remote_endpoint_.address().to_string() returns "acfc:4000:0:0:7800::%2885986016" which I can't identify as something useful
Also I recognized that my io_service is stopping all the time, but in my understanding it should run all the time, right?
I already thought about referencing this in the callback function bind with a shared_from_this ptr, but since I have a real instance of the udp_server class until I leave my program I can't think of a good reason to do that.
Can someone explain thy this failure occurs, what these errors tell me about my code or what I can do to avoid them?
Nevermind, Rubberduck debugging was enough. I just read the line
but since I have a real instance of the udp_server class until I leave my program I can't think of a good reason to do that.
and noticed, that I actually didn't have this and this was the error.

How to find out how much data was sent through a Boost ASIO TCP socket connection?

I have some shared pointers to boost::asio::io_service, boost::asio::ip::tcp::endpoint, boost::asio::ip::tcp::acceptor and boost::asio::ip::tcp::socket. I accept users connection and pass shared_ptr of the socket to some class of mine. It does its work.
Now what I want is simple - count my traffic. I want to get information of how much data was sent and received during that connection. How to get such information from accepted Boost ASIO TCP socket?
Assuming you use asynchronous methods, the completion handler given to async_read will indicate the number of bytes received. Similarly, the completion handler given to async_write will indicate the number of bytes written. It would be trivial to maintain a running counter as a member of a class where you bind methods as the previously described completion handlers.
#include <boost/asio.hpp>
#include <iostream>
class Socket
{
public:
Socket(
boost::asio::io_service& io_service
) :
_socket( io_service ),
_counter( 0 )
{
}
void readHandler(
const boost::system::error_code& error,
std::size_t bytes_transferred
)
{
_counter += bytes_transferred;
}
void writeHHandler(
const boost::system::error_code& error,
std::size_t bytes_transferred
)
{
_counter += bytes_transferred;
}
private:
boost::asio::ip::tcp::socket _socket;
std::size_t _counter;
};
int
main()
{
boost::asio::io_service io_service;
Socket foo( io_service );
}