I want to create a server async with multi threads.
When I create a thread_group and waiting for some connections in asynchronous way. My program don't wait and termine immediatly.
void Server::configServer() {
_ip = boost::asio::ip::address_v4::from_string("127.0.0.1");
boost::asio::ip::tcp::resolver resolver(_io_service);
_endpoint = *resolver.resolve({tcp::v4(), _port});
std::cout << "Server address: " << _ip.to_string() << ":" << _port << std::endl;
_acceptor.close();
_acceptor.open(_endpoint.protocol());
_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
_acceptor.bind(_endpoint);
_acceptor.listen();
for (int i = 0; i < 8; ++i) {
_threads.create_thread(boost::bind(&boost::asio::io_service::run, &_io_service));
}
_threads.join_all();
std::cout << "Server is set up" << std::endl;
run();
}
void Server::run() {
Connection::pointer newConnection = Connection::create(_acceptor.get_io_service());
std::cout << "Server is running" << std::endl;
_acceptor.async_accept(newConnection->socket(),
boost::bind(&Server::handleAccept, this, newConnection,
boost::asio::placeholders::error));
}
void Server::handleAccept(Connection::pointer newConnection, const boost::system::error_code& error) {
if (!error) {
std::cout << "Reçu un client!" << std::endl;
newConnection->start();
run();
}
}
Can you tell me what am I doing wrong ?
run works as long as there are any pending tasks/handlers to be processed.
In your case you started run, then first async_ method was called. So run ends immediately due to no handlers to be called.
You should init some asynchronous task, then invoke run or use object called work guard. You didn't specify which version of Boost you use, but there are two options:
in olders io_service/io_context::work (ref)
current, executor_work_guard (ref)
In your class you can add executor_work_guard as additional member variable:
class Server {
boost::asio::io_context _io_service;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> guard;
Server() : ...., guard(boost::asio::make_work_guard(_io_service)) {
}
};
with this approach, run doesn't return even if there are no handlers to be processed.
I'm trying to write a TCP client using several different examples using Asio from Boost 1.60. The connection works properly for probably 30 seconds or so, but disconnects with the error:
The network connection was aborted by the local system
I've attempted to set up a "ping/pong" setup to keep the connection alive but it still terminates. The only previous Stack Overflow answers I've found suggested using Boost's shared_from_this and a shared pointer, which I've adapted my code to use. But the problem persists.
Setting up the Connection object and its thread:
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver res(ios);
boost::shared_ptr<Connection> conn = boost::shared_ptr<Connection>(new Connection(ios));
conn->Start(res.resolve(boost::asio::ip::tcp::resolver::query("myserver", "10635")));
boost::thread t(boost::bind(&boost::asio::io_service::run, &ios));
Here's the relevant portions of the Connection class (I made sure to use shared_from_this() everywhere else, too):
class Connection : public boost::enable_shared_from_this<Connection>
{
public:
Connection(boost::asio::io_service &io_service)
: stopped_(false),
socket_(io_service),
deadline_(io_service),
heartbeat_timer_(io_service)
{
}
void Start(tcp::resolver::iterator endpoint_iter)
{
start_connect(endpoint_iter);
deadline_.async_wait(boost::bind(&Connection::check_deadline, shared_from_this()));
}
private:
void start_read()
{
deadline_.expires_from_now(boost::posix_time::seconds(30));
boost::asio::async_read_until(socket_, input_buffer_, 0x1f,
boost::bind(&Connection::handle_read, shared_from_this(), _1));
}
void handle_read(const boost::system::error_code& ec)
{
if (stopped_)
return;
if (!ec)
{
std::string line;
std::istream is(&input_buffer_);
std::getline(is, line);
if (!line.empty())
{
std::cout << "Received: " << line << "\n";
}
start_read();
}
else
{
// THIS IS WHERE THE ERROR IS LOGGED
std::cout << "Error on receive: " << ec.message() << "\n";
Stop();
}
}
void check_deadline()
{
if (stopped_)
return;
if (deadline_.expires_at() <= deadline_timer::traits_type::now())
{
socket_.close();
deadline_.expires_at(boost::posix_time::pos_infin);
}
deadline_.async_wait(boost::bind(&Connection::check_deadline, shared_from_this()));
}
};
The issue turned out to be on the server's end. The server wasn't sending the "pong" response to the client's ping properly, so the async_read_until() call never finished and consequently never reset the deadline timer.
I would like to implement a Boost Asio pattern using a thread for GUI and a worker thread for some socket IO.
The worker thread will use boost::asio::io_service to manage a socket client. All operations on sockets will be performed by the worker thread only.
The GUI thread needs to send and receive messages from the worker thread.
I can't exactly figure how to implement this pattern using Boost Asio.
I've already implemented the socket communication in the standard Asio way (I call io_service.run() from the worker thread and I use async_read_some/async_send). I don't need strands because io_service.run() is called from the worker thread only.
Now I'm trying to add the cross thread message queue. How I can I implement it?
Should I run the io_service from the GUI thread too?
Or should I just use strands with post to post messages from the GUI thread to the worker thread (without calling io_service.run() or io_service.poll_one() from the GUI thread), and use the operating system's GUI message loop to post messages from the worker thread to the GUI thread?
If I need to call io_service.run() or io_service.poll_one() from the GUI thread too, do I need to use strands on the socket operations, since the io_service is shared between two threads?
EDIT: to clarify my question, I would like to do whatever I can, to implement the message queue, using Boost Asio, relying on other libraries only if Boost Asio can't do the job.
Message passing is fairly generic. There are various ways to approach the problem, and the solution will likely be dependent on the desired behavioral details. For example, blocking or non-blocking, controlling memory allocation, context, etc.
Boost.Lockfree provides thread-safe lock-free non-blocking queues for singe/multi consumer/producers. It tends to lend itself fairly nicely to event loops, where it is not ideal for the consumer to be blocked, waiting for the producer to signal a synchronization construct.
boost::lockfree::queue<message_type> worker_message_queue;
void send_worker_message(const message_type& message)
{
// Add message to worker message queue.
worker_message_queue.push(message);
// Add work to worker_io_service that will process the queue.
worker_io_service.post(&process_message);
}
void process_message()
{
message_type message;
// If the message was not retrieved, then return early.
if (!worker_message_queue.pop(message)) return;
...
}
Alternatively, Boost.Asio's io_service can function as a queue. The message just needs to be bound to the specified handler.
void send_worker_message(const message_type& message)
{
// Add work to worker_io_service that will process the message.
worker_io_service.post(boost::bind(&process_message, message));
}
void process_message(message_type& message)
{
...
}
This comment suggest that the desire is more than message passing. It sounds as though the end goal is to allow one thread to cause another thread to invoke arbitrary functions.
If this is the case, then consider:
Using Boost.Signals2 for a managed signals and slots implementation. This allows arbitrary functions to register with a signal.
Using Boost.Asio's io_service to setup signal emissions. If the GUI thread and worker thread each have their own io_service, then the worker thread can post a handler into the GUI thread's io_service that will emit a signal. In the GUI thread's main loop, it will poll the io_service, emit the signal, and cause slots to be invoked from within the GUI thread's context.
Here is complete example where two threads pass a message (as an unsigned int) to one another, as well as causing arbitrary functions to be invoked within another thread.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/signals2.hpp>
#include <boost/thread.hpp>
/// #brief io_service dedicated to gui.
boost::asio::io_service gui_service;
/// #brief io_service dedicated to worker.
boost::asio::io_service worker_service;
/// #brief work to keep gui_service from stopping prematurely.
boost::optional<boost::asio::io_service::work> gui_work;
/// #brief hello slot.
void hello(int x)
{
std::cout << "hello with " << x << " from thread " <<
boost::this_thread::get_id() << std::endl;
}
/// #brief world slot.
void world(int x)
{
std::cout << "world with " << x << " from thread " <<
boost::this_thread::get_id() << std::endl;
}
/// #brief Type for signals.
typedef boost::signals2::signal<void (int)> signal_type;
void emit_then_notify_gui(signal_type& signal, unsigned int x);
/// #brief Emit signals then message worker.
void emit_then_notify_worker(signal_type& signal, unsigned int x)
{
// Emit signal, causing registered slots to run within this thread.
signal(x);
// If x has been exhausted, then cause gui service to run out of work.
if (!x)
{
gui_work = boost::none;
}
// Otherwise, post work into worker service.
else
{
std::cout << "GUI thread: " << boost::this_thread::get_id() <<
" scheduling other thread to emit signals" << std::endl;
worker_service.post(boost::bind(
&emit_then_notify_gui,
boost::ref(signal), --x));
}
}
/// #brief Emit signals then message worker.
void emit_then_notify_gui(signal_type& signal, unsigned int x)
{
// Emit signal, causing registered slots to run within this thread.
signal(x);
// If x has been exhausted, then cause gui service to run out of work.
if (!x)
{
gui_work = boost::none;
}
// Otherwise, post more work into gui.
else
{
std::cout << "Worker thread: " << boost::this_thread::get_id() <<
" scheduling other thread to emit signals" << std::endl;
gui_service.post(boost::bind(
&emit_then_notify_worker,
boost::ref(signal), --x));
}
}
void worker_main()
{
std::cout << "Worker thread: " << boost::this_thread::get_id() << std::endl;
worker_service.run();
}
int main()
{
signal_type signal;
// Connect slots to signal.
signal.connect(&hello);
signal.connect(&world);
boost::optional<boost::asio::io_service::work> worker_work(
boost::ref(worker_service));
gui_work = boost::in_place(boost::ref(gui_service));
std::cout << "GUI thread: " << boost::this_thread::get_id() << std::endl;
// Spawn off worker thread.
boost::thread worker_thread(&worker_main);
// Add work to worker.
worker_service.post(boost::bind(
&emit_then_notify_gui,
boost::ref(signal), 3));
// Mocked up GUI main loop.
while (!gui_service.stopped())
{
// Do other GUI actions.
// Perform message processing.
gui_service.poll_one();
}
// Cleanup.
worker_work = boost::none;
worker_thread.join();
}
And its output:
GUI thread: b7f2f6d0
Worker thread: b7f2eb90
hello with 3 from thread b7f2eb90
world with 3 from thread b7f2eb90
Worker thread: b7f2eb90 scheduling other thread to emit signals
hello with 2 from thread b7f2f6d0
world with 2 from thread b7f2f6d0
GUI thread: b7f2f6d0 scheduling other thread to emit signals
hello with 1 from thread b7f2eb90
world with 1 from thread b7f2eb90
Worker thread: b7f2eb90 scheduling other thread to emit signals
hello with 0 from thread b7f2f6d0
world with 0 from thread b7f2f6d0
If you have only one worker, then it's rather easy.
ASIO's handlers are executed by the thread(s) that are calling io_service.run(). In your case, that means that only one thread, the worker one, can execute callback handler. So you need not to worry about thread safety here.
Your GUI thread, assuming that it has access to one's socket, can call boost::asio::async_write() without problem. The callback handler, however, will be executed in the worker thread.
From my experience (admitedly limited), I used this pattern:
The business logic thread (could be your GUI thread) can schedule a write to one of its client easily, by calling boost::asio::async_write(): the worker thread will take care of it.
The worker thread start some boost::asio::async_read(), and could be building "business logic packet". What I mean here, is that it construct meaningfull message (could be a subclass of a custom class Packet or Event or w/e you what) from raw data.
When the worker thread has enough data to build such a message, it does, and then enqueue it to a thread-safe queue that the GUI thread will be pulling.
The GUI (or business logic) thread then process the message.
Let me know if its not clear / if I can be of more help.
The way that I exchange messages between 2+ threads is to use a container like a queue and store them in there and then use an event to notify the worker thread to wake up and process them. Here is an example:
void SSLSocket::SendToServer(const int bytesInMsg, Byte* pBuf)
{
// This method creates a msg object and saves it in the SendMsgQ object.
//
Message* pMsg = Message::GetMsg(this, bytesInMsg, pBuf);
SendMsgQ.Push(pMsg);
// Signal the send worker thread to wake up and send the msg to the server.
SetEvent(hEvent);
}
In the header file:
std::queue<Message*> SendMsgQueue; // Queue of msgs to send to the server.
The above code is for Microsoft VC++. You might have to use a different class or methods if your development environment is different. But, the idea should be the same.
Edit - More Complete Code Example
#include "StdAfx.h"
#include "SSLSocket.h"
boost::shared_ptr< boost::asio::io_service > SSLSocket::IOService;
bool SSLSocket::LobbySocketOpen = false;
SSLSocket* SSLSocket::pSSLLobby = 0;
int SSLSocket::StaticInit = 0;
Callback SSLSocket::CallbackFunction;
BufferManagement SSLSocket::BufMang;
volatile bool SSLSocket::ReqAlive = true;
Logger SSLSocket::Log;
HANDLE SSLSocket::hEvent;
bool SSLSocket::DisplayInHex;
ConcurrentMsgQueue SSLSocket::SendMsgQ;
bool SSLSocket::RcvThreadCreated = 0;
BufferManagement* Message::pBufMang;
bool SSLSocket::ShuttingDown = false;
std::vector<SSLSocket *> SocketList;
SSLSocket::SSLSocket(const bool logToFile, const bool logToConsole, const bool displayInHex,
const LogLevel levelOfLog, const string& logFileName, const int bufMangLen) : pSocket(0)
{
// SSLSocket Constructor.
// If the static members have not been intialized yet, then initialize them.
LockCode = new Lock();
if (!StaticInit)
{
SocketList.push_back(this);
DisplayInHex = displayInHex;
BufMang.Init(bufMangLen);
Message::SetBufMang(&BufMang);
// This constructor enables logging according to the vars passed in.
Log.Init(logToFile, logToConsole, levelOfLog, logFileName);
StaticInit = 1;
hEvent = CreateEvent(NULL, false, false, NULL);
// Define the ASIO IO service object.
// IOService = new boost::shared_ptr<boost::asio::io_service>(new boost::asio::io_service);
boost::shared_ptr<boost::asio::io_service> IOServ(new boost::asio::io_service);
IOService = IOServ;
pSSLLobby = this;
}
}
SSLSocket::~SSLSocket(void)
{
if (pSocket)
delete pSocket;
if (--StaticInit == 0)
CloseHandle(hEvent);
}
void SSLSocket::Connect(SSLSocket* psSLS, const string& serverPath, string& port)
{
// Connects to the server.
// serverPath - specifies the path to the server. Can be either an ip address or url.
// port - port server is listening on.
//
try
{
LockCode->Acquire(); // Single thread the code.
// If the user has tried to connect before, then make sure everything is clean before trying to do so again.
if (pSocket)
{
delete pSocket;
pSocket = 0;
}
// If serverPath is a URL, then resolve the address.
if ((serverPath[0] < '0') || (serverPath[0] > '9')) // Assumes that the first char of the server path is not a number when resolving to an ip addr.
{
// Create the resolver and query objects to resolve the host name in serverPath to an ip address.
boost::asio::ip::tcp::resolver resolver(*IOService);
boost::asio::ip::tcp::resolver::query query(serverPath, port);
boost::asio::ip::tcp::resolver::iterator EndpointIterator = resolver.resolve(query);
// Set up an SSL context.
boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client);
// Specify to not verify the server certificiate right now.
ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
// Init the socket object used to initially communicate with the server.
pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx);
//
// The thread we are on now, is most likely the user interface thread. Create a thread to handle all incoming socket work messages.
// Only one thread is created to handle the socket I/O reading and another thread is created to handle writing.
if (!RcvThreadCreated)
{
WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this));
RcvThreadCreated = true;
WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this));
}
// Try to connect to the server. Note - add timeout logic at some point.
boost::asio::async_connect(pSocket->lowest_layer(), EndpointIterator,
boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error));
}
else
{
// serverPath is an ip address, so try to connect using that.
//
stringstream ss1;
boost::system::error_code EC;
ss1 << "SSLSocket::Connect: Preparing to connect to game server " << serverPath << " : " << port << ".\n";
Log.LogString(ss1.str(), LogInfo);
// Create an endpoint with the specified ip address.
const boost::asio::ip::address IP(boost::asio::ip::address::from_string(serverPath));
int iport = atoi(port.c_str());
const boost::asio::ip::tcp::endpoint EP(IP, iport);
// Set up an SSL context.
boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client);
// Specify to not verify the server certificiate right now.
ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
// Init the socket object used to initially communicate with the server.
pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx);
//
// Try to connect to the server. Note - add timeout logic at some point.
pSocket->next_layer().connect(EP, EC);
if (EC)
{
// Log an error. This worker thread should exit gracefully after this.
stringstream ss;
ss << "SSLSocket::Connect: connect failed to " << sClientIp << " : " << uiClientPort << ". Error: " << EC.message() + ".\n";
Log.LogString(ss.str(), LogError);
}
stringstream ss;
ss << "SSLSocket::Connect: Calling HandleConnect for game server " << serverPath << " : " << port << ".\n";
Log.LogString(ss.str(), LogInfo);
HandleConnect(EC);
}
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::Connect: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
LockCode->Release();
}
void SSLSocket::SendToServer(const int bytesInMsg, Byte* pBuf)
{
// This method creates a msg object and saves it in the SendMsgQ object.
// sends the number of bytes specified by bytesInMsg in pBuf to the server.
//
Message* pMsg = Message::GetMsg(this, bytesInMsg, pBuf);
SendMsgQ.Push(pMsg);
// Signal the send worker thread to wake up and send the msg to the server.
SetEvent(hEvent);
}
void SSLSocket::SendWorkerThread(SSLSocket* psSLS)
{
// This thread method gets called to process the messages to be sent to the server.
//
// Since this has to be a static method, call a method on the class to handle server requests.
psSLS->ProcessSendRequests();
}
void SSLSocket::ProcessSendRequests()
{
// This method handles sending msgs to the server.
//
std::stringstream ss;
DWORD WaitResult;
Log.LogString("SSLSocket::ProcessSendRequests: Worker thread " + Logger::NumberToString(boost::this_thread::get_id()) + " started.\n", LogInfo);
// Loop until the user quits, or an error of some sort is thrown.
try
{
do
{
// If there are one or more msgs that need to be sent to a server, then send them out.
if (SendMsgQ.Count() > 0)
{
Message* pMsg = SendMsgQ.Front();
SSLSocket* pSSL = pMsg->pSSL;
SendMsgQ.Pop();
const Byte* pBuf = pMsg->pBuf;
const int BytesInMsg = pMsg->BytesInMsg;
boost::system::error_code Error;
LockCode->Acquire(); // Single thread the code.
try
{
boost::asio::async_write(*pSSL->pSocket, boost::asio::buffer(pBuf, BytesInMsg), boost::bind(&SSLSocket::HandleWrite, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::ProcessSendRequests: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
}
ss.str(std::string());
ss << "SSLSocket::ProcessSendRequests: # bytes sent = " << BytesInMsg << "\n";
Log.LogString(ss.str(), LogDebug2);
Log.LogBuf(pBuf, BytesInMsg, DisplayInHex, LogDebug3);
LockCode->Release();
}
else
{
// Nothing to send, so go into a wait state.
WaitResult = WaitForSingleObject(hEvent, INFINITE);
if (WaitResult != 0L)
{
Log.LogString("SSLSocket::ProcessSendRequests: WaitForSingleObject event error. Code = " + Logger::NumberToString(GetLastError()) + ". \n", LogError);
}
}
} while (ReqAlive);
Log.LogString("SSLSocket::ProcessSendRequests: Worker thread " + Logger::NumberToString(boost::this_thread::get_id()) + " done.\n", LogInfo);
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::ProcessSendRequests: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::HandleWrite(const boost::system::error_code& error, size_t bytesTransferred)
{
// This method is called after a msg has been written out to the socket. Nothing to do really since reading is handled by the HandleRead method.
//
std::stringstream ss;
try
{
if (error)
{
ss << "SSLSocket::HandleWrite: failed - " << error.message() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleHandshake: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::RcvWorkerThread(SSLSocket* psSLS)
{
// This is the method that gets called when the receive thread is created by this class.
// This thread method focuses on processing messages received from the server.
//
// Since this has to be a static method, call an instance method on the class to handle server requests.
psSLS->InitAsynchIO();
}
void SSLSocket::InitAsynchIO()
{
// This method is responsible for initiating asynch i/o.
boost::system::error_code Err;
string s;
stringstream ss;
//
try
{
ss << "SSLSocket::InitAsynchIO: Worker thread - " << Logger::NumberToString(boost::this_thread::get_id()) << " started.\n";
Log.LogString(ss.str(), LogInfo);
// Enable the handlers for asynch i/o. The thread will hang here until the stop method has been called or an error occurs.
// Add a work object so the thread will be dedicated to handling asynch i/o.
boost::asio::io_service::work work(*IOService);
IOService->run();
Log.LogString("SSLSocket::InitAsynchIO: receive worker thread done.\n", LogInfo);
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::InitAsynchIO: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::HandleConnect(const boost::system::error_code& error)
{
// This method is called asynchronously when the server has responded to the connect request.
std::stringstream ss;
try
{
if (!error)
{
LockCode->Acquire(); // Single thread the code.
pSocket->async_handshake(boost::asio::ssl::stream_base::client,
boost::bind(&SSLSocket::HandleHandshake, this, boost::asio::placeholders::error));
LockCode->Release();
ss << "SSLSocket::HandleConnect: From worker thread " << Logger::NumberToString(boost::this_thread::get_id()) << ".\n";
Log.LogString(ss.str(), LogInfo);
}
else
{
// Log an error. This worker thread should exit gracefully after this.
ss << "SSLSocket::HandleConnect: connect failed. Error: " << error.message() + ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::InitAsynchIO: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::HandleHandshake(const boost::system::error_code& error)
{
// This method is called asynchronously when the server has responded to the handshake request.
std::stringstream ss;
try
{
if (!error)
{
// Try to send the first message that the server is expecting. This msg tells the server we want to connect.
//
unsigned char Msg[5] = {0x17, 0x00, 0x00, 0x00, 0x06};
boost::system::error_code Err;
//
if (pSSLLobby == this)
LobbySocketOpen = true;
sClientIp = pSocket->lowest_layer().remote_endpoint().address().to_string();
uiClientPort = pSocket->lowest_layer().remote_endpoint().port();
ReqAlive = true;
LockCode->Acquire(); // Single thread the code.
int Count = boost::asio::write(*pSocket, boost::asio::buffer(Msg), boost::asio::transfer_exactly(5), Err);
if (Err)
{
ss << "SSLSocket::HandleHandshake: write failed - " << error.message() << ".\n";
Log.LogString(ss.str(), LogInfo);
}
HandleFirstWrite(Err, Count);
LockCode->Release();
ss.str("");
ss << "SSLSocket::HandleHandshake: From worker thread " << boost::this_thread::get_id() << ".\n";
}
else
{
ss << "SSLSocket::HandleHandshake: failed - " << error.message() << ".\n";
IOService->stop();
}
Log.LogString(ss.str(), LogInfo);
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleHandshake: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::HandleFirstWrite(const boost::system::error_code& error, size_t bytesTransferred)
{
// This method is called after a msg has been written out to the socket. This method is only called from HandleHandShake.
std::stringstream ss;
try
{
if (!error)
{
// Notify the UI that we are now connected. Create a 6 byte msg for this.
pDataBuf = BufMang.GetPtr(6);
BYTE* p = pDataBuf;
// Create msg type 500
*p = 244;
*++p = 1;
CallbackFunction(this, 2, (void*)pDataBuf);
// Get the 1st 4 bytes of the next msg, which is always the length of the msg.
pDataBuf = BufMang.GetPtr(MsgLenBytes);
try
{
boost::asio::async_read(*pSocket, boost::asio::buffer(pDataBuf, MsgLenBytes), boost::bind(&SSLSocket::HandleRead, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleFirstWrite: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
else
{
ss << "SSLSocket::HandleFirstWrite: failed - " << error.message() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleFirstWrite: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::HandleRead(const boost::system::error_code& error, size_t bytesTransferred)
{
// This method is called to process an incoming message.
//
std::stringstream ss;
int ByteCount;
try
{
// ss << "SSLSocket::HandleRead: From worker thread " << boost::this_thread::get_id() << ".\n";
// Log.LogString(ss.str(), LogInfo);
// Set to exit this thread if the user is done.
if (!ReqAlive)
{
// IOService->stop();
return;
}
if (!error)
{
// Get the number of bytes in the message.
if (bytesTransferred == 4)
{
ByteCount = BytesToInt(pDataBuf);
}
else
{
// Call the C# callback method that will handle the message.
ss << "SSLSocket::HandleRead: From worker thread " << boost::this_thread::get_id() << "; # bytes transferred = " << bytesTransferred << ".\n";
Log.LogString(ss.str(), LogDebug2);
if (bytesTransferred > 0)
{
Log.LogBuf(pDataBuf, (int)bytesTransferred, true, LogDebug3);
Log.LogString("SSLSocket::HandleRead: sending msg to the C# client.\n\n", LogDebug2);
CallbackFunction(this, bytesTransferred, (void*)pDataBuf);
}
else
{
// # of bytes transferred = 0. Don't do anything.
bytesTransferred = 0; // For debugging.
}
// Prepare to read in the next message length.
ByteCount = MsgLenBytes;
}
pDataBuf = BufMang.GetPtr(ByteCount);
boost::system::error_code Err;
try
{
boost::asio::async_read(*pSocket, boost::asio::buffer(pDataBuf, ByteCount), boost::bind(&SSLSocket::HandleRead,
this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleRead: threw this error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
}
}
else
{
Log.LogString("SSLSocket::HandleRead failed: " + error.message() + "\n", LogError);
Stop();
}
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::HandleRead: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
void SSLSocket::Stop()
{
// This method calls the shutdown method on the socket in order to stop reads or writes that might be going on. If this is not done, then an exception will be thrown
// when it comes time to delete this object.
//
boost::system::error_code EC;
try
{
// This method can be called from the handler as well. So once the ShuttingDown flag is set, don't go throught the same code again.
if (ShuttingDown)
return;
LockCode->Acquire(); // Single thread the code.
if (!ShuttingDown)
{
ShuttingDown = true;
pSocket->next_layer().cancel();
pSocket->shutdown(EC);
if (EC)
{
stringstream ss;
ss << "SSLSocket::Stop: socket shutdown error - " << EC.message() << ".\n";
}
else
{
pSocket->next_layer().close();
}
delete pSocket;
pSocket = 0;
ReqAlive = false;
SetEvent(hEvent);
IOService->stop();
LobbySocketOpen = false;
WorkerThreads.join_all();
}
LockCode->Release();
delete LockCode;
LockCode = 0;
}
catch (std::exception& e)
{
stringstream ss;
ss << "SSLSocket::Stop: threw an error - " << e.what() << ".\n";
Log.LogString(ss.str(), LogError);
Stop();
}
}
So, in answer to your question about whether you have to use a queue or not. In your comment to Xaqq, you said "I need to exchange messages between the two threads." So using a container like a queue is how messages can be passed to another thread for processing. If you don't like the STL containers, Boost does have some. As far as I know, there is no Boost ASIO internal container that can be accessed. Storing and passing the messages around is something you have to do in your code.
One last note about the call to io_service::run. It will only block while there is work to do. See this link. In my example code above, a work item is added to the io_service object before the run method is called, so it will block indefinitely - which is what I want. If I really wanted only one thread, then what I might do is set up the worker thread to call the run method with a work object so that it would block indefinitely. This would handle all asynchronous I/O coming from and going to the server. Inside the class, I would write an interface method or two so that the gui can send data to the server. These methods could use the async write .vs. the synch write method and thus would return right away - so your gui won't block long. You would need to write a HandleWrite method. My code does not do much with it - just logs an error if one occurs.
I'm having an issue creating a really simple TCP based server-client connection using boost asio. When I get a connection from a client on my server and get into the method that handles the async_read_some I check for an error, and am always getting error 1236, which gives the message "The network connection was aborted by the local system."
I've just started working with boost, so I'm not really familiar with how the libraries work and what I could have done wrong. I've provided a cut down version of my code below:
/*Client connection code*/
ClientConnection::ClientConnection(boost::asio::io_service& io_service) : m_Socket(io_service)
{
}
ClientConnection::ClientConnectionPointer ClientConnection::Create(boost::asio::io_service& io_service)
{
return ClientConnection::ClientConnectionPointer(new ClientConnection(io_service));
}
void ClientConnection::handle_write(const boost::system::error_code& error, size_t bytes_transferred)
{
//once we've written our packet, just wait for more
m_Socket.async_read_some(boost::asio::buffer(m_IncomingBytesBuffer, MAX_BYTES_LENGTH),
boost::bind(&ClientConnection::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void ClientConnection::handle_read(const boost::system::error_code& error, size_t bytes_transferred)
{
if(!error)
{
//deal with the data that comes in here
}
else
{
std::cout << "Error reading port data" << std::endl;
std::cout << error.message() << std::endl;
}
}
tcp::socket& ClientConnection::GetSocket(void)
{
return m_Socket;
}
void ClientConnection::RunClient(void)
{
std::cout << "Client connected." << std::endl;
//start by reading data from the connection
m_Socket.async_read_some(boost::asio::buffer(m_IncomingBytesBuffer, MAX_BYTES_LENGTH),
boost::bind(&ClientConnection::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
/*Listener server code here*/
BarcodeServer::BarcodeServer(boost::asio::io_service& io_service) : m_acceptor(io_service, tcp::endpoint(tcp::v4(), SERVER_PORT_NUMBER))
{
start_accepting_connections();
}
void BarcodeServer::start_accepting_connections(void)
{
std::cout << "Waiting for a connection." << std::endl;
ClientConnection::ClientConnectionPointer new_connection = ClientConnection::Create(m_acceptor.get_io_service());
m_acceptor.async_accept(new_connection->GetSocket(), boost::bind(&BarcodeServer::handle_accepted_connection, this, new_connection, boost::asio::placeholders::error));
}
void BarcodeServer::handle_accepted_connection(ClientConnection::ClientConnectionPointer new_connection, const boost::system::error_code& error)
{
if(!error)
{
new_connection->RunClient();
}
start_accepting_connections();
}
/*main code here*/
try
{
boost::asio::io_service io_service;
BarcodeServer server(io_service);
io_service.run();
}
catch(std::exception& e)
{
cout << "Error when running server:" << endl;
cout << e.what() << endl;
return RETURN_CODE_SERVER_RUN_ERROR;
}
return RETURN_CODE_SUCCESS;
Most of this code is prety much just lifted straight from examples on the boost website, so I'm guessing I've just done something silly somewhere, but I've looked over the code a few times and can't figure out where.
Any help would be much appreciated.
The lifetime of ClientConnection ends after handle_accepted_connection() exits, because all the instances of shared_ptr<ClientConnection> go out of scope and get destroyed.
To avoid this situation, you can either use shared_from_this idiom within ClientConnection member-functions or store 1 shared_ptr<ClientConnection> in some "connection manager".
I'm trying to create a TCP server where the Start() method blocks until a connection is accepted, and then begins a series of asynchronous reads. I have the following code, and when I connect using telnet I get this output:
Waiting for a new connection
Connection accepted
terminate called throwing an exceptionAbort trap: 6
Here is the code:
void SocketReadThread::Start()
{
bzero(m_headerBuffer, HEADER_LEN);
m_running = true;
asio::io_service ios;
asio::ip::tcp::acceptor acp (ios,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), GUI_PORT));
asio::ip::tcp::socket sock(ios);
std::cout << "Waiting for a new connection" << std::endl;
acp.accept(sock);
std::cout << "Connection accepted" << std::endl;
asio::async_read(sock, asio::buffer(m_headerBuffer, HEADER_LEN),
boost::bind(&SocketReadThread::handleReadHeader, shared_from_this(),
asio::placeholders::error));
ios.run();
}
void SocketReadThread::handleReadHeader(const system::error_code& error)
{
std::cout << "Read two bytes!" << std::endl;
}
You should wrap your main() function in try {...} catch (std::exception& e) { cout << e.what(); } block.
You're probably doing something scary (and awesome) to the stack by declaring your ReadHandler incorrectly. Even if you ignore some parameters, the signature must be:
void handler (
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes copied into the
// buffers. If an error occurred,
// this will be the number of
// bytes successfully transferred
// prior to the error.
);