I'm developing a 3d (first/third person) game and I'm trying to make it multiplayer using TCP sockets. I'm using the boost asio library for this, and I'm in a little over my head. I've played with the tutorials and examples a bit on the boost asio doc page and they compiled/ran/worked just fine, I'm just a little confused as to how everything works.
Right now I'm just trying to make the server accept messages from the client, and print the message after receiving it. When I execute the code below (it compiles/links/runs fine), nothing happens. More specifically, the client appears to successfully send the message, and the server never seems to receive the message.
Client code:
ClientFramework::ClientFramework() :
mResolver(mIOService)
{
}
bool ClientFramework::Initialize()
{
try
{
tcp::resolver::query query("localhost", "daytime");
tcp::resolver::iterator it = mResolver.resolve(query);
tcp::socket socket(mIOService);
boost::asio::connect(socket, it);
std::string s = "hello world";
boost::system::error_code e;
socket.write_some(boost::asio::buffer(s.c_str(), s.size()), e);
if (e)
{
throw boost::system::system_error(e);
}
} catch (std::exception& e)
{
gLog << LOG_ERROR << e.what() << "\n";
}
return true;
}
Server code:
ServerFramework::ServerFramework() :
mAcceptor(mIOService, tcp::endpoint(tcp::v4(), 13))
{
}
bool ServerFramework::Initialize()
{
mIOService.run();
StartAccept();
return true;
}
void ServerFramework::StartAccept()
{
Connection::ptr conn =
Connection::create(mAcceptor.get_io_service());
mAcceptor.async_accept(conn->Socket(),
boost::bind(&ServerFramework::HandleAccept, this, conn,
boost::asio::placeholders::error));
}
void ServerFramework::HandleAccept(Connection::ptr conn,
const boost::system::error_code& error)
{
if (!error)
{
conn->Initialize();
}
StartAccept();
}
Connection::ptr Connection::create(boost::asio::io_service& io_service)
{
return ptr(new Connection(io_service));
}
tcp::socket& Connection::Socket()
{
return mSocket;
}
void Connection::Initialize()
{
boost::asio::async_read(mSocket, boost::asio::buffer(buf, BUFFER_SIZE),
boost::bind(&Connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
Connection::Connection(boost::asio::io_service& io_service) :
mSocket(io_service)
{
}
void Connection::handle_read(const boost::system::error_code& e, size_t size)
{
std::string s(buf, size);
gLog << LOG_INFO << s << "\n";
boost::asio::async_read(mSocket, boost::asio::buffer(buf, BUFFER_SIZE),
boost::bind(&Connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
It does not look like your io_service has any work to do when you invoke run().
bool ServerFramework::Initialize()
{
mIOService.run(); // <-- you don't check the return value here
StartAccept();
return true;
}
it will return the number of handlers executed, I suspect it is zero. Try invoking it after async_accept()
bool ServerFramework::Initialize()
{
StartAccept();
mIOService.run();
return true;
}
Though, it isn't entirely obvious by your limited code snippets where you invoke ServerFramework::Initialize(). I suggest editing your question with a short, self contained, correct example that we can compile with little to no effort. Your current code will not compile without additional boilerplate stuff, like main().
Related
I've created a simple wrapper for boost::asio library. My wrapper consists of 4 main classes: NetServer (server), NetClient (client), NetSession (client/server session) and Network (composition class of these three which also includes all callback methods).
The problem is that the first connection client/server works flawlessly, but when I then stop server, start it again and then try to connect the client, the server just doesn't recognize the client. It seems like the acceptor callback isn't called. And client does connect to server, because first - the connection goes without errors, second - when I close the server's program, the client receives the error message WSAECONNRESET.
I've created test program which emulates the procedure written above. It does following:
Starts the server
Starts the client
Client succesfully connects to server
Stops the server
Client receives the error and disconnects itself
Starts the server again
Client again succesfully connects to server
BUT SERVER DOESN'T CALL THE ACCEPTOR CALLBACK ANYMORE
It means that in point 3 the acceptor succesfully calls the callback function, but in point 7 the acceptor doesn't call the callback.
I think I do something wrong in stop()/start() method of the server, but I can't figure out what's exactly wrong.
The source of the NetServer class:
NetServer::NetServer(Network& netRef) : net{ netRef }
{
acceptor = std::make_unique<boost::asio::ip::tcp::acceptor>(ioc);
}
NetServer::~NetServer(void)
{
ioc.stop();
if (threadStarted)
{
th.join();
threadStarted = false;
}
if (active)
stop();
}
int NetServer::start(void)
{
assert(getAcceptHandler() != nullptr);
assert(getHeaderHandler() != nullptr);
assert(getDataHandler() != nullptr);
assert(getErrorHandler() != nullptr);
closeAll();
try
{
ep = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), srvPort);
acceptor->open(ep.protocol());
acceptor->bind(ep);
acceptor->listen();
initAccept();
}
catch (system::system_error& e)
{
return e.code().value();
}
if (!threadStarted)
{
th = std::thread([this]()
{
ioc.run();
});
threadStarted = true;
}
active = true;
return Network::NET_OK;
}
int NetServer::stop(void)
{
ioc.post(boost::bind(&NetServer::_stop, this));
return Network::NET_OK;
}
void NetServer::_stop(void)
{
boost::system::error_code ec;
acceptor->close(ec);
for (auto& s : sessions)
closeSession(s.get(), false);
active = false;
}
void NetServer::initAccept(void)
{
sock = std::make_shared<asio::ip::tcp::socket>(ioc);
acceptor->async_accept(*sock.get(), [this](const boost::system::error_code& error)
{
onAccept(error, sock);
});
}
void NetServer::onAccept(const boost::system::error_code& ec, SocketSharedPtr sock)
{
if (ec.value() == 0)
{
if (accHandler())
{
addSession(sock);
initAccept();
}
}
else
getErrorHandler()(nullptr, ec);
}
SessionPtr NetServer::addSession(SocketSharedPtr sock)
{
std::lock_guard<std::mutex> guard(mtxSession);
auto session = std::make_shared<NetSession>(sock, *this, true);
sessions.insert(session);
session->start();
return session;
}
SessionPtr NetServer::findSession(const SessionPtr session)
{
for (auto it = std::begin(sessions); it != std::end(sessions); it++)
if (*it == session)
return *it;
return nullptr;
}
bool NetServer::closeSession(const void *session, bool erase /* = true */)
{
std::lock_guard<std::mutex> guard(mtxSession);
for (auto it = std::begin(sessions); it != std::end(sessions); it++)
if (it->get() == session)
{
try
{
it->get()->getSocket()->cancel();
it->get()->getSocket()->shutdown(asio::socket_base::shutdown_send);
it->get()->getSocket()->close();
it->get()->getSocket().reset();
}
catch (system::system_error& e)
{
UNREFERENCED_PARAMETER(e);
}
if (erase)
sessions.erase(*it);
return true;
}
return false;
}
void NetServer::closeAll(void)
{
using namespace boost::placeholders;
std::lock_guard<std::mutex> guard(mtxSession);
std::for_each(sessions.begin(), sessions.end(), boost::bind(&NetSession::stop, _1));
sessions.clear();
}
bool NetServer::write(const SessionPtr session, std::string msg)
{
if (SessionPtr s = findSession(session); s)
{
s->addMessage(msg);
if (s->canWrite())
s->write();
return true;
}
return false;
}
This is the output from the server:
Enter 0 - server, 1 - client: 0
1. Server started
3. Client connected to server
Stopping server....
4. Server stopped
Net error, server, acceptor: ERROR_OPERATION_ABORTED
Net error, server, ERROR_OPERATION_ABORTED
Client session deleted
6. Server started again
(HERE SHOULD BE "8. Client again connected to server", but the server didn't recognize the reconnected client!)
And from the client:
Enter 0 - server, 1 - client: 1
2. Client started and connected to server
Net error, client: ERROR_FILE_NOT_FOUND
5. Client disconnected from server
Waiting 3 sec before reconnect...
Connecting to server...
7. Client started and connected to server
(WHEN I CLOSE THE SERVER WINDOW, I RECVEIVE HERE THE "Net error, client: WSAECONNRESET" MESSAGE - it means client was connected to server anyhow!)
If the code of NetClient, NetSession and Network is necessary, just let me know.
Thanks in advance
Wow. There's a lot to unpack. There is quite a lot of code smell that reminds me of some books on Asio programming that turned out to be... not excellent in my previous experience.
I couldn't give any real advice without grokking your code, which requires me to review in-depth and add missing bits. So let me just provide you with my reviewed/fixed code first, then we'll talk about some of the details.
A few areas where you seemed to have trouble making up your mind:
whether to use a strand or to use mutex locking
whether to use async or sync (e.g. closeSession is completely synchronous and blokcing)
whether to use shared-pointers for lifetime or not: on the one hand you have NetSesion support shared_from_this, but on the other hand you are keeping them alive in a sessions collection.
whether to use smart pointers or raw pointers (sp.get() is a code smell)
whether to use void* pointers or forward declared structs for opaque implementation
whether to use exceptions or to use error codes. Specifically:
return e.code().value();
is a Very Bad Idea. Just return error_code already. Or just propagate the exception.
judging from the use, my best bet is that sessions is std::set<SessionPtr>. Then it's funny that you're doing linear searches. In fact, findSession could be:
SessionPtr findSession(SessionPtr const& session) {
std::lock_guard guard(mtxSessions);
return sessions.contains(session)? session: nullptr;
}
In fact, given some natural invariants, it could just be
auto findSession(SessionPtr s) { return std::move(s); }
Note as well, you had forgotten to lock the mutex in findSession
closeSession completely violates Law Of Demeter, 6*3 times over if you will. In my example I make it so SessHandle is a weak pointer to NetSession and you can just write:
for (auto& handle : sessions)
if (auto sess = handle.lock())
sess->close();
Of course, sess->close() should not block
Also, it should correctly synchronize on the session e.g. using the sessions strand:
void close() {
return post(sock_.get_executor(), [this, self = shared_from_this()] {
error_code ec;
if (!ec) sock_.cancel(ec);
if (!ec) sock_.shutdown(tcp::socket::shutdown_send, ec);
if (!ec) sock_.close(ec);
});
}
If you insist, you can make it so the caller can still await the result and receive any exceptions:
std::future<void> close() {
return post(
sock_.get_executor(),
std::packaged_task<void()>{[this, self = shared_from_this()] {
sock_.cancel();
sock_.shutdown(tcp::socket::shutdown_send);
sock_.close();
}});
}
Honestly, that seems overkill since you never look at the return value anyways.
In general, I recommend leaving socket::close() to the destructor. It avoids a specific class of race-conditions on socket handles.
Don't use boolean flags (isThreadActive is better replaced with th.joinable())
apparently you had NetSession::stop which I imagine did largely the same as closeSession but in the right place? I replaced it with the new NetSession::close
subtly when accHandler returned false, you would exit the accept loop alltogether. I doubt that was on purpose
try to minimize time under locks:
std::future<void> close() {
return post(
sock_.get_executor(),
std::packaged_task<void()>{[this, self = shared_from_this()] {
sock_.cancel();
sock_.shutdown(tcp::socket::shutdown_send);
sock_.close();
}});
}
I will show you how to do without the lock entirely instead.
Demo Listing
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <deque>
#include <iostream>
#include <iomanip>
#include <set>
using namespace std::chrono_literals;
using namespace std::placeholders;
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;
static inline std::ostream debug(std::cerr.rdbuf());
struct Network {
static constexpr error_code NET_OK{};
};
struct NetSession; // opaque forward reference
struct NetServer;
using SessHandle = std::weak_ptr<NetSession>; // opaque handle
using Sessions = std::set<SessHandle, std::owner_less<>>;
struct NetSession : std::enable_shared_from_this<NetSession> {
NetSession(tcp::socket&& s, NetServer& srv, bool)
: sock_(std::move(s))
, srv_(srv) {
debug << "New session from " << getPeer() << std::endl;
}
void start() {
post(sock_.get_executor(),
std::bind(&NetSession::do_read, shared_from_this()));
}
tcp::endpoint getPeer() const { return peer_; }
void close() {
return post(sock_.get_executor(), [this, self = shared_from_this()] {
debug << "Closing " << getPeer() << std::endl;
error_code ec;
if (!ec) sock_.cancel(ec);
if (!ec) sock_.shutdown(tcp::socket::shutdown_send, ec);
// if (!ec) sock_.close(ec);
});
}
void addMessage(std::string msg) {
post(sock_.get_executor(),
[this, msg = std::move(msg), self = shared_from_this()] {
outgoing_.push_back(std::move(msg));
if (canWrite())
write_loop();
});
}
private:
// assumed on (logical) strand
bool canWrite() const { // FIXME misnomer: shouldStartWriteLoop()?
return outgoing_.size() == 1;
}
void write_loop() {
if (outgoing_.empty())
return;
async_write(sock_, asio::buffer(outgoing_.front()),
[this, self = shared_from_this()](error_code ec, size_t) {
if (!ec) {
outgoing_.pop_front();
write_loop();
}
});
}
void do_read() {
incoming_.clear();
async_read_until(
sock_, asio::dynamic_buffer(incoming_), "\n",
std::bind(&NetSession::on_read, shared_from_this(), _1, _2));
}
void on_read(error_code ec, size_t);
tcp::socket sock_;
tcp::endpoint peer_ = sock_.remote_endpoint();
NetServer& srv_;
std::string incoming_;
std::deque<std::string> outgoing_;
};
using SessionPtr = std::shared_ptr<NetSession>;
using SocketSharedPtr = std::shared_ptr<tcp::socket>;
struct NetServer {
NetServer(Network& netRef) : net{netRef} {}
~NetServer()
{
if (acceptor.is_open())
acceptor.cancel(); // TODO seems pretty redundant
stop();
if (th.joinable())
th.join();
}
std::function<bool()> accHandler;
std::function<void(SocketSharedPtr, error_code)> errHandler;
// TODO headerHandler
std::function<void(SessionPtr, error_code, std::string)> dataHandler;
error_code start() {
assert(accHandler);
assert(errHandler);
assert(dataHandler);
closeAll(sessions);
error_code ec;
if (!ec) acceptor.open(tcp::v4(), ec);
if (!ec) acceptor.bind({{}, srvPort}, ec);
if (!ec) acceptor.listen(tcp::socket::max_listen_connections, ec);
if (!ec) {
do_accept();
if (!th.joinable()) {
th = std::thread([this] { ioc.run(); }); // TODO exceptions!
}
}
if (ec && acceptor.is_open())
acceptor.close();
return ec;
}
void stop() { //
post(ioc, std::bind(&NetServer::do_stop, this));
}
void closeSession(SessHandle handle, bool erase = true) {
post(acceptor.get_executor(), [=, this] {
if (auto s = handle.lock()) {
s->close();
}
if (erase) {
sessions.erase(handle);
}
});
}
void closeAll() {
post(acceptor.get_executor(), [this] {
closeAll(sessions);
sessions.clear();
});
}
// TODO FIXME is the return value worth it?
bool write(SessionPtr const& session, std::string msg) {
return post(acceptor.get_executor(),
std::packaged_task<bool()>{std::bind(
&NetServer::do_write, this, session, std::move(msg))})
.get();
}
// compare
void writeAll(std::string msg) {
post(acceptor.get_executor(),
std::bind(&NetServer::do_write_all, this, std::move(msg)));
}
private:
Network& net;
asio::io_context ioc;
tcp::acceptor acceptor{ioc}; // active -> acceptor.is_open()
std::thread th; // threadActive -> th.joinable()
Sessions sessions;
std::uint16_t srvPort = 8989;
// std::mutex mtxSessions; // note naming; also replaced by logical strand
// assumed on acceptor logical strand
void do_accept() {
acceptor.async_accept(
make_strand(ioc), [this](error_code ec, tcp::socket sock) {
if (ec.failed()) {
return errHandler(nullptr, ec);
}
if (accHandler()) {
auto s = std::make_shared<NetSession>(std::move(sock),
*this, true);
sessions.insert(s);
s->start();
}
do_accept();
});
}
SessionPtr do_findSession(SessionPtr const& session) {
return sessions.contains(session) ? session : nullptr;
}
bool do_write(SessionPtr session, std::string msg) {
if (auto s = do_findSession(session)) {
s->addMessage(std::move(msg));
return true;
}
return false;
}
void do_write_all(std::string msg) {
for(auto& handle : sessions)
if (auto sess = handle.lock())
do_write(sess, msg);
}
static void closeAll(Sessions const& sessions) {
for (auto& handle : sessions)
if (auto sess = handle.lock())
sess->close();
}
void do_stop()
{
if (acceptor.is_open()) {
error_code ec;
acceptor.close(ec); // TODO error handling?
}
closeAll(sessions); // TODO FIXME why not clear sessions?
}
};
// Implementation must be after NetServer definition:
void NetSession::on_read(error_code ec, size_t) {
if (srv_.dataHandler)
srv_.dataHandler(shared_from_this(), ec, std::move(incoming_));
if (!ec)
do_read();
}
int main() {
Network net;
NetServer srv{net};
srv.accHandler = [] { return true; };
srv.errHandler = [](SocketSharedPtr, error_code ec) {
debug << "errHandler: " << ec.message() << std::endl;
};
srv.dataHandler = [](SessionPtr sess, error_code ec, std::string msg) {
debug << "dataHandler: " << sess->getPeer() << " " << ec.message()
<< " " << std::quoted(msg) << std::endl;
};
srv.start();
std::this_thread::sleep_for(10s);
std::cout << "Shutdown started" << std::endl;
srv.writeAll("We're going to shutdown, take care!\n");
srv.stop();
}
Live Demo:
I refer to the example from boost example:async_tcp_client.cpp. This example shows how to set timeout for aync_read. So I write a test program to test async_write timeout according to this example.
The write code is:
bool AsioAsyncTCPClientImpl::send(const uint8_t* data, int32_t length)
{
if (!m_isConnected || length <= 0) return false;
m_deadline.expires_after(std::chrono::seconds(5));
boost::system::error_code ec;
boost::asio::async_write(m_client, boost::asio::buffer(data, length),
std::bind(&AsioAsyncTCPClientImpl::handleWrite, this, std::placeholders::_1, std::placeholders::_2));
return true;
}
the handleWrite code is:
void AsioAsyncTCPClientImpl::handleWrite(const boost::system::error_code& ec, std::size_t len)
{
if (!m_started) return;
if (ec == boost::asio::error::eof)
{
fireConnectionCallback(ConnectionState::Disconnected);
return;
}
if (ec)
{
fireErrorCallback(ec);
return;
}
m_deadline.expires_at(boost::asio::steady_timer::time_point::max());
}
From my test, if I disable the network or pull out the cable of the PC where the server is running, the async_write will always completed as normal, so the timeout set is not working. I am wondering if I miss something, hope some one familiar with this could give me some clue, Thanks for advance!
Update
The async_wait code:
bool AsioAsyncTCPClientImpl::start()
{
if (m_started) return true;
connect();
m_deadline.async_wait(std::bind(&AsioAsyncTCPClientImpl::checkTimeout, this));
m_started = true;
m_ioLoopThread = std::thread(&AsioAsyncTCPClientImpl::loopProcess, this);
return true;
}
void AsioAsyncTCPClientImpl::checkTimeout()
{
if (!m_started) return;
if (m_deadline.expiry() <= boost::asio::steady_timer::clock_type::now())
{
std::cout << "wait timeout" << std::endl;
disconnect();
m_deadline.expires_at(boost::asio::steady_timer::time_point::max());
}
m_deadline.async_wait(std::bind(&AsioAsyncTCPClientImpl::checkTimeout, this));
}
And I put the run method of io_context in a thread, I am not sure if this is right way to do it, because I don't want to run io_context.run() in main function.
void AsioAsyncTCPClientImpl::loopProcess()
{
while(m_started)
{
m_context.run();
}
std::cout << "loop process exited" << std::endl;
}
You never await the timer.
Something like
m_deadline.async_wait(
std::bind(&AsioAsyncTCPClientImpl::handleTimer, this, boost::asio::placeholders::errpr));
And then
void AsioAsyncTCPClientImpl::handleTimer(boost::system::error_code ec) {
if (!ec) {
std::cout << "Timeout expired" << std::endl;
m_client.cancel();
}
}
I am trying to write my socket class (code below).
At last everything works:reconnection, connection, message send, message receive
But I noticed memory leak when I repeat TCPSocketBody::Connect(const std::string &adress, const std::string &port) if for example host is unreachable. Size of my application is growing.
I discovered that when I remove line:
thread_io_service = boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_global));
the problem disappears. But I need this line. What I am doing wrong?
I checked from command line number of thread in my application and it always is 1 or 2.
#include "TCPSocketBody.h"
TCPSocketBody::TCPSocketBody() : socket_(io_service_global),
resolver(io_service_global),
connected(false),
expectedMessage(0)
{
}
void TCPSocketBody::Close()
{
io_service_global.post(boost::bind(&TCPSocketBody::DoClose, this));
}
void TCPSocketBody::Connect(const std::string &adress, const std::string &port)
{
io_service_global.reset();
iterator = resolver.resolve({adress, port});
boost::asio::async_connect(socket_, iterator,
boost::bind(&TCPSocketBody::HandleConnect, this,
boost::asio::placeholders::error));
socket_.set_option(boost::asio::ip::tcp::no_delay(true));
thread_io_service = boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_global));
}
void TCPSocketBody::HandleConnect(const boost::system::error_code& error)
{
if (!error)
{
connected = true;
boost::asio::async_read(socket_,
boost::asio::buffer(data_to_read, MessageCoder::BufferSize()), boost::asio::transfer_all(),
boost::bind(&TCPSocketBody::HandleReadHeader, this,
boost::asio::placeholders::error));
} else
{
Close();
}
}
void TCPSocketBody::HandleReadHeader(const boost::system::error_code& error)
{
expectedMessage = MessageCoder::HeaderToVal(data_to_read);
if (expectedMessage > MessageCoder::MaxMessageSize())
{
expectedMessage = 0;
Close();
} else
{
boost::asio::async_read(socket_,
boost::asio::buffer(data_to_read, expectedMessage), boost::asio::transfer_all(),
boost::bind(&TCPSocketBody::HandleReadMessage, this,
boost::asio::placeholders::error));
}
}
void TCPSocketBody::HandleReadMessage(const boost::system::error_code& error)
{
expectedMessage = 0;
boost::asio::async_read(socket_,
boost::asio::buffer(data_to_read, MessageCoder::BufferSize()), boost::asio::transfer_all(),
boost::bind(&TCPSocketBody::HandleReadHeader, this,
boost::asio::placeholders::error));
}
void TCPSocketBody::WriteMessage(char *dataToSend)
{
io_service_global.post(boost::bind(&TCPSocketBody::Write, this, dataToSend));
}
void TCPSocketBody::Write(char *dataToSend)
{
data = dataToSend;
boost::asio::async_write(socket_,
boost::asio::buffer(data, std::strlen(data)),
boost::bind(&TCPSocketBody::HandleWrite, this,
boost::asio::placeholders::error));
}
void TCPSocketBody::HandleWrite(const boost::system::error_code& error)
{
if (!error)
{
}
else
{
Close();
}
}
void TCPSocketBody::DoClose()
{
socket_.close();
connected = false;
}
Without the header file, it is hard to be certain. I suspect that thread_io_service is a member variable. A second call to 'Connect' will overwrite the existing value without destroying the object. Any memory allocated within the object will be leaked.
Perhaps try making a std::vector of thread_io_service and push_back each new thread on the connect call. The vector will destroy the contained objects when it gets destructed.
Valgrind can likely pinpoint the issue with more detail.
boost::asio::async_read doesn't call the handler and keeps receiving, am trying to receive some buffers that I don't know it's length , but max is 1024
#include "AsyncConnection.h"
AsyncConnection::AsyncConnection(boost::asio::io_service& io_service)
: socket(io_service)
{
}
AsyncConnection::~AsyncConnection()
{
}
AsyncConnection::Pointer AsyncConnection::Create(boost::asio::io_service& io_service){
return Pointer(new AsyncConnection(io_service));
}
boost::asio::ip::tcp::socket& AsyncConnection::GetSocket(){
return socket;
}
void AsyncConnection::BeginReceive(){
boost::asio::async_read(socket, boost::asio::buffer(buffer, 1024),
boost::bind(&AsyncConnection::EndReceive, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void AsyncConnection::EndReceive(const boost::system::error_code& error, std::size_t bytes_transferred){
if (!error){
}
else{
std::cout << error.message() << std::endl;
}
}
it never calls the EndReceive , my guess is it's keeping receiving until the buffer is full?! how to fix that tho!
Come across the following codes (from user368831) which is what I am looking for. I have modified a little to make it a threaded TCP session that listen and read for connection and data while the main loop can do other tasks.
class CSession
{
public:
CSession(boost::asio::io_service& io_service) : m_Socket(io_service)
{}
tcp::socket& socket() return m_Socket;
void start()
{
boost::asio::async_read_until(m_Socket, m_Buffer, " ",
boost::bind(&CSession::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
ostringstream ss;
ss << &m_Buffer;
m_RecvMsg = ss.str();
std::cout << "handle_read():" << m_RecvMsg << std::endl;
}
else
delete this;
}
private:
boost::asio::streambuf m_Buffer;
tcp::socket m_Socket;
string m_RecvMsg;
};
class CTcpServer
{
public:
CTcpServer(short port)
: m_Acceptor(m_IOService, tcp::endpoint(tcp::v4(), port)),
m_Thread(boost::bind(&boost::asio::io_service::run, &m_IOService))
{
CSession* new_session = new CSession(m_IOService);
m_Acceptor.async_accept(new_session->socket(),
boost::bind(&CTcpServer::handle_accept, this, new_session,
boost::asio::placeholders::error));
};
void handle_accept(CSession* new_session, const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
new_session = new CSession(m_IOService);
m_Acceptor.async_accept(new_session->socket(),
boost::bind(&CTcpServer::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
else
delete new_session;
}
private:
boost::asio::io_service m_IOService;
tcp::acceptor m_Acceptor;
boost::thread m_Thread;
};
void main()
{
:
CTcpServer *server = new CTcpServer(6002); // tcp port 6002
/* How to get the incoming data sent from the client here?? */
// string message;
// while(1)
// {
// if ( server->incomingData(message) )
// {
// std::cout << "Data recv: " << message.data() << std::endl;
// }
// :
// : // other tasks
// :
// }
}
However, how do I code incomingData() in the main loop such that it will monitor the data from the client and return true whenever handle_read() is called?
Can use Boost::signals library in this case?
This code is frankly horrible. There are memory leaks galore because of the way you are using raw pointers. Asio works best with shared_ptrs, it needs guarantees about the lifetimes of objects. I suggest you throw this code away, and start by looking at asio's simple enough to follow examples.
As for the method you want to code - that's not the way it works, you should put that logic in handle_read. handle_read will get called when you have a full message according to your protocol, you should put the logic you want to happen in this method - not in the main while loop. In your main thread, you should simply call io_service::run().