I am trying to Create a simple Tcp Server in C++ using Boost ASio Library. I wrote two classes TcpConnection and TcpServer.
The behaviour I need is that The Tcp Server should be able to send messages to all the connected clients and clients should be able to register/deregister with the server.
I was able to achieve the message sending from server. I was unsuccessful with the reading from clients part. My client is written in java, using apache mina.
Server Code
message = message + "\r\n";
const int bytesToSend = message.length();
boost::system::error_code error;
boost::asio::write(socket, boost::asio::buffer(message, bytesToSend), boost::asio::transfer_all(), error);
Client code
ConnectFuture future = ioConnector.connect(new InetSocketAddress(Port),
new TriggerReceiverHandler();
System.out.println("Message Receiver started and listening on port "+ Port);
IoSession session = future.getSession();
session.write(new String("TEst Message From Client"));
On the server the code to read the messages is done using the async_read
boost::array<char, 1> buf;
boost::asio::async_read(socket, boost::asio::buffer(buf),
boost::bind(&TcpConnection::handleRead, this, buf, boost::asio::placeholders::error));
void TcpConnection::handleRead(boost::array<char, 1> buf, const boost::system::error_code& error)
{
if(!error)
{
std::cout << "Message: " << buf.data() << std::endl;
}
else
{
std::cout << "Error occurred." << std::endl;
}
}
But the handleRead is not getting called when I trigger a message by writing to the session from the client. Please tell me if I am doing anything wrong.
I would appreciate any Help..Please let me know if any further info is needed.
Thanks in advance.
Firstly this appears to be incorrect!
You are declaring an array of size 1! I’d suggest something bigger!
Aside from the buffer, I can’t see anything wrong with your code, just check that you are not interleaving
async_readcalls on the same socket.