Hey guys, i'm a newbie to async-programming, this is probably a stupid question, but it indeed drove me crazy!!
Here's the code (it just modified a bit from boost.asio's sample):
server.cpp:
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 10000)),limit(0)
{
start_accept();
}
private:
void start_accept()
{
while(1)
{
if(limit <= 10)
{
std::cout << limit << std::endl;
break;
}
}
tcp::socket* socket = new tcp::socket(acceptor_.io_service());
acceptor_.async_accept(*socket,
boost::bind(&tcp_server::handle_accept, this, boost::asio::placeholders::error));
}
void handle_accept(const boost::system::error_code& error)
{
if (!error)
{
++limit ;
start_accept();
}
}
tcp::acceptor acceptor_;
int limit;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
client.cpp:
int main(int argc, char* argv[])
{
int i = 0;
while(1)
{
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("127.0.0.1", "10000");
tcp::resolver::iterator endpoint_iterator =resolver.resolve(query);
tcp::endpoint endpoint = *endpoint_iterator;
tcp::socket socket(io_service);
socket.close();
socket.connect(endpoint);
std::cout << i++ << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
return 0;
}
I just wanna limit server to accept 10 client.
However, client cout the error information after it cout "amazing" 210 (never more or less) continuous numbers.
What happend??
I've changed server.cpp a bit. First reconfigured acceptor_ on constructor. Removed while loop, added acceptor_.close();
#include <boost/asio/io_service.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using namespace boost::asio;
using namespace boost::asio::ip;
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service),limit(0)
{
tcp::endpoint endpoint(tcp::v4(), 10000);
acceptor_.open(endpoint.protocol());
acceptor_.bind(endpoint);
acceptor_.listen(1); //accept 1 connection at a time
start_accept();
}
private:
void start_accept()
{
tcp::socket* socket = new tcp::socket(acceptor_.io_service());
acceptor_.async_accept(*socket,
boost::bind(
&tcp_server::handle_accept,
this,
socket,
boost::asio::placeholders::error));
}
void handle_accept(tcp::socket* s, const boost::system::error_code& error)
{
if (!error)
{
++limit;
if (limit < 9)
{
start_accept();
}
else
{
acceptor_.close();
}
}
}
tcp::acceptor acceptor_;
int limit;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
I suppose, default acceptor can async_accept 200 connection events at a time. You open a socket and close it from the client side in an infinite loop. As a result you open and close a connection 200 times, but it is still 1 connection, 1 socket.
Capping it to 1 by calling listen(1), would force the acceptor to fire an event. You increase the count, then client closes the connection. This way you correctly count each connection event.
Last note: async io uses 1 thread to process connection events, retrieved data etc... Thus, use of mutexes are not necessary.
Related
The server starts and accepts connections, all clients, even if more than 10 are connected, send a message but there is no response.
The read and write function uses the index of the received client's account and works with it. Therefore, there is an additional parameter in the headers.
We accept the connection and pass its number to the header and there with the socket of this number we are working.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <clocale>
#include <vector>
#include <conio.h>
using namespace boost::asio;
using namespace std;
class tcp_server
{
private:
io_service service;
int port;
enum { buff_size = 1024 };
ip::tcp::endpoint endpoint;
ip::tcp::acceptor acceptor;
int countClients = 0;
int accept_i = 0;
struct client
{
ip::tcp::socket sock;
char buff[buff_size] = { };
};
vector<client> clients;
public:
tcp_server(io_service& service, int port) : service(), acceptor(service), endpoint(ip::tcp::v4(), port)
{
this->port;
acceptor.open(endpoint.protocol());
acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
clients.reserve(10);
}
void start()
{
start_service_in_thread();
}
void start_service_in_thread()
{
for (int i = 0; i < 10; ++i)
boost::thread(service_func_for_thread);
for (int i = 0; i < 10; ++i)
{
boost::thread(acceptor_func_for_thread);
accept_i++;
}
}
void service_func_for_thread()
{
service.run();
}
void accept_handler(const boost::system::error_code& error)
{
if (!error)
{
countClients++;
do_read_this(countClients - 1);
}
else
{
cout << "Acceptor error\n";
cout << error.message() << endl;
}
}
void acceptor_func_for_thread()
{
acceptor.async_accept(
clients[accept_i].sock,
boost::bind(&tcp_server::accept_handler, this, boost::asio::placeholders::error)
);
}
void do_read_this(int thisClientIndex)
{
clients[thisClientIndex].sock.async_read_some(
buffer(clients[thisClientIndex].buff),
boost::bind(&tcp_server::read_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
thisClientIndex)
);
}
void read_handler(const boost::system::error_code& error, size_t bytes_transferred, int thisClientIndex)
{
if (!error)
{
clients[thisClientIndex].sock.async_write_some(
buffer(clients[thisClientIndex].buff),
boost::bind(&tcp_server::write_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
thisClientIndex)
);
}
else
{
cout << "Error reading from socket\n";
cout << error.message() << endl;
}
}
void write_handler(const boost::system::error_code& error, size_t bytes_transferred, int thisClientIndex)
{
if (!error)
{
do_read_this(thisClientIndex);
}
else
{
cout << "Error write in socket\n";
cout << error.message() << endl;
}
}
};
int main(int argc, char *argv[])
{
try
{
setlocale(LC_ALL, "Rus");
io_service service;
tcp_server* server = new tcp_server{ service, 5000 };
server->start();
service.run();
}
catch (exception& ex)
{
cout << "Exception: " << ex.what();
}
return 0;
}
The client connects to the server and when it sends a connection, no response is received.
Please help.
service.run(); in main has nothing to do so it returns immediately so main returns causing program to end.
Creating background threads is not necessary here.
You are (again) creating a temporary objects boost::thread that immediately go out of scope. And unless BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE is specified you will end up with a bunch of detached threads.
When the io_service::run() method has no work to do, it returns.
You should either
post() at least one task to the io_service before calling run(),
or "lock" it with io_service::work
io_service service;
boost::asio::io_service::work work(service);
The latter requires a call to service.stop() to cause run() to exit, otherwise it will run eternally.
Note however: you don't really need two io_services or any threads in an async application.
I am trying to make my first TCP server using boost::asio. The server will listen to clients and if it receives message "MESSAGE_SEND_A:", it should send the following message back to the client: "A|A|A|A|A|A". If it receives message "MESSAGE_SEND_B:", then accordingly it should send another message to the client: "B|B|B|B|B|B".
Now, I have been studying the Boost TCP server tutorial and it is more or less clear:
EDIT: Code is rewritten based on comments
#include <ctime>
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
// Start reading messages from the server
start_read();
if (messageFromClient_ == "MESSAGEA:")
{
messageToClient_ = "A|A|A|A|A|A|A|A|A|A";
}
else if (messageFromClient_ == "MESSAGEB:")
{
messageToClient_ = "B|B|B|B|B|B|B|B|B|B";
}
boost::asio::async_write(socket_, boost::asio::buffer(messageToClient_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
tcp_connection(boost::asio::io_service& io_service) : socket_(io_service)
{
}
// Reading messages from the server
void start_read()
{
// Start an asynchronous operation to read a newline-delimited message.
// When read, handle_read should kick in
boost::asio::async_read(socket_, input_buffer_,
boost::asio::transfer_at_least(1),
boost::bind(&tcp_connection::handle_read, this,
boost::asio::placeholders::error));
}
// When stream is received, handle the message from the client
void handle_read(const boost::system::error_code& ec)
{
//if (stopped_)
// return;
// Making the message nil every time the function starts. Do I need it???????
messageFromClient_ = "";
if (!ec)
{
// Extract the newline-delimited message from the buffer.
std::string line;
std::istream is(&input_buffer_);
std::getline(is, line);
// Empty messages are heartbeats and so ignored.
if (!line.empty())
{
messageFromClient_ = line;
std::cout << "Received: " << line << "\n";
}
start_read();
}
else
{
std::cout << "Error on receive: " << ec.message() << "\n";
}
}
void handle_write(const boost::system::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
}
tcp::socket socket_;
std::string messageToClient_;
boost::asio::streambuf input_buffer_;
std::string messageFromClient_;
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 7767))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_user_read(const boost::system::error_code& err,
std::size_t bytes_transferred)
{
}
void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
start_accept();
}
}
tcp::acceptor acceptor_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
The code is compiled well on Qt, but gives me:
Error on receive: Operation canceled
every time I am trying to send a message from my client (iPad).
Thank you!
the function start() should asynchronously read from the socket, while invoking handle_read() function when data received.
Please review this example:
http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp
This is my current code for the server. I connect to the server using telnet.
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class Connection
{
public:
Connection(boost::asio::io_service& io_service) : socket_(io_service)
{
}
void start()
{
AsyncRead();
}
tcp::socket& socket()
{
return socket_;
}
private:
void AsyncRead()
{
boost::asio::async_read(socket_, boost::asio::buffer(data_, max_length),
[this](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
std::cout << data_ << std::endl;
}
});
}
tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
};
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
private:
void start_accept()
{
Connection* connection = new Connection(io_service_);
acceptor_.async_accept(connection->socket(), [this, connection](boost::system::error_code ec)
{
//std::cout << ec.message() << std::endl;
if(!ec)
{
std::cout << "Connected." << std::endl;
connection->start();
}
else
{
delete connection;
}
start_accept();
});
}
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;
server s(io_service, 7899);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
Instead of async_read I use async_read_some I can get the first message sent from telnet and thats it.
Any suggestions on what I am doing wrong ?
Thanks.
async_read will read the number of bytes specified in the length parameter. You aren't seeing the first message because async_read is still waiting to read max_length bytes. This question discusses similar behaviour
Basically I have a client where I send a string of 10 bytes hellohello to a server and within the server I expect the reply to be 0123456789 back to the client but instead I get hellohello again? I changed the char data_ to char data_out on line 58 in the tcp_server.cpp because I thought that was the place to send packet data out? I'm pretty sure that gets called but for some reason things aren't working like I thought.
This is the server output,
handle read: bytes_transferred10
10
handle write:
0123456789
handle read: bytes_transferred0
I also wonder why did handle read: bytes_transferred0 get called again?
This is the client output,
Enter message: hellohello
Reply is: hellohello
Process returned 0 (0x0) execution time : 6.484 s
Press any key to continue.
This is the tcp_server.cpp
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class session
{
public:
session(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
socket_.async_read_some(boost::asio::buffer(data_, max_length),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred);
private:
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
std::cout<<"handle read: bytes_transferred"<<bytes_transferred<<std::endl;
if (!error)
{
read_handler(error, bytes_transferred);
boost::asio::async_write(socket_,
boost::asio::buffer(data_, bytes_transferred),
boost::bind(&session::handle_write, this,
boost::asio::placeholders::error));
}
else
{
delete this;
}
}
void handle_write(const boost::system::error_code& error)
{
std::cout<<"handle write: "<<std::endl;
data_out = {'0','1','2','3','4','5','6','7','8','9'};
if (!error)
{
std::cout<<data_out<<std::endl;
socket_.async_read_some(boost::asio::buffer(data_out, max_length),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
delete this;
}
}
tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
char data_out[max_length];
};
void session::read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
std::cout<<bytes_transferred<<std::endl;
}
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
private:
void start_accept()
{
session* new_session = new session(io_service_);
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void handle_accept(session* new_session,
const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
}
else
{
delete new_session;
}
start_accept();
}
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main()
{
try
{
boost::asio::io_service io_service;
server s(io_service, 4000);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
tcp_client.cpp
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), "127.0.0.1", "4000");
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
using namespace std; // For strlen.
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));
char reply[max_length];
size_t reply_length = boost::asio::read(s,boost::asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
Your comment
I think handle_read() calls handle_write() recursively?
is close but not quite correct as there is no recursion here. The documentation explains this nicely:
Regardless of whether the asynchronous operation completes immediately
or not, the handler will not be invoked from within this function.
Invocation of the handler will be performed in a manner equivalent to
using boost::asio::io_service::post().
Added emphasis is mine. Instead of recursion, It is better to think of these concepts as chaining since one operation such as async_write() is initiated in the handler of another, such as async_read(). The exact specifics depend on the protocol in use.
If you want the server to send the string 0123456789 to the client, fill your buffer before invoking async_write().
I have a problem, i have a TCP connection between a client and a server , when the client initialize he send a message to the server and the serveur answer by a welcom message .
All this work fine on a local network.
So my problem is that I use async_write and async_read ( because I need my server to be asynchronous )
My client send the message to the server , the server see it and answer but my client never get the welcom message .
Otherwise when I close my server , the client received the welcome message .
here is my server code :
main.cpp
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service, 7171);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
tcp_server
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service, int port) // (1)
: m_acceptor(io_service, tcp::endpoint(tcp::v4(), port))
{
std::cout << "Port : " << port << std::endl;
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection = tcp_connection::create(m_acceptor.io_service());
m_acceptor.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) // (4)
{
if (!error)
{
std::cout << "Get one client!" << std::endl;
new_connection->start();
start_accept(); // (5)
}
}
tcp::acceptor m_acceptor;
};
tcp_connection
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& ios)
{
pointer new_connection(new tcp_connection(ios) );
return new_connection;
}
tcp::socket& socket()
{
return m_socket;
}
void do_read() // (1)
{
boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer), // (3)
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error)
);
}
void start()
{
m_message = "Welcome on the server \n";
boost::asio::async_write(m_socket, boost::asio::buffer(m_message),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error)
);
}
private:
tcp_connection(boost::asio::io_service& io_service)
: m_socket(io_service)
{ }
void handle_write(const boost::system::error_code& error)
{
std::cout << "handle_write : "<< m_message << std::endl;
if (!error)
do_read(); // (2)
else
std::cout << error.message() << std::endl;
}
void handle_read(const boost::system::error_code& error) // (6)
{
std::cout << "handle read" << m_buffer.data() <<std::endl;
if (!error)
do_read();
else
close();
}
void close() // (7)
{
m_socket.close();
}
tcp::socket m_socket;
std::string m_message;
boost::array<char, 128> m_buffer;
};
I don't understand why ?
And How can I avoid this ?
Please, the manual of async_read:
This function is used to asynchronously read a certain number of bytes
of data from a stream. The function call always returns immediately.
The asynchronous operation will continue until one of the following
conditions is true:
The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
An error occurred.
In your case, none of the 2 conditions are satisfied - until the peer closes the socket.
You should use async_read_some instead (or async_read_until, but it might be a bit more complicated).