dimanche 19 juin 2016

How to asynchronously communicate between server and client


Okay, this code handles the server side communication between a server and client. I am not too familiar with boost::asio, but I tried my best following the several tutorials. However, there remains one problem when trying to communicate between my client (I haven't built it yet so I'm using putty) and the server. The server only receives data when the client closes it's connection. I'm just wondering if that is suppose to be the case, and if so how do I respond to client side requests?

This is the function to start the server (it is shortened, i removed the error handling mechanism)

void Initialize(){
    boost::asio::io_service ioservice;
    Network network(ioservice);
    ioservice.run();
}

Here is the function that starts accepting connections

void Network::StartAccept(){
  Connection::pointer new_connection = Connection::create(acceptor_.get_io_service());

  acceptor_.async_accept(new_connection->getSocket(),
     boost::bind(&Network::HandleAccept, this, 
     new_connection, boost::asio::placeholders::error));
}

This function handles the accept and starts another accept again

void Network::HandleAccept(Connection::pointer new_connection, const boost::system::error_code & error){
if (!error)
{
    //sio::cout() is one of my functions that automatically time stamps everything and ends the line if needed
    sio::cout("Client Connected from Origin: ", false);
    sio::cout(new_connection->getSocket().remote_endpoint().address().to_string(), true, false);
    new_connection->start();
}
else {
    sio::cout("Could Not Accept Connection to Client");
}
StartAccept();

}

This function handles client I/O

void Connection::start() {
//message_ = "Hello World";

//boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&Connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
boost::asio::async_read(socket_, msg, boost::bind(&Connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

}

I would like to be able to write "hello world" to the client and then read in what the client says, however if I do async_write (which is commented out), it disconnects the client and async_read spits out an error because there is no connection

TLDR how do I keep the connection open, or am I not suppose to


Aucun commentaire:

Enregistrer un commentaire