Skip to content

Instantly share code, notes, and snippets.

@ahundt
Created February 27, 2015 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahundt/a436d1506b282664ec9a to your computer and use it in GitHub Desktop.
Save ahundt/a436d1506b282664ec9a to your computer and use it in GitHub Desktop.
//
// echo_server.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2015 Andrew Hundt
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/signal_set.hpp>
#include <iostream>
#include <memory>
#include <azmq/socket.hpp>
#include <flatbuffers/flatbuffers.h>
class session : public std::enable_shared_from_this<session>
{
public:
explicit session(azmq::socket socket)
: socket_(std::move(socket)),
strand_(socket_.get_io_service())
{
}
void SendFlatBuffer(std::shared_ptr<flatbuffers::FlatBufferBuilder> fbbP)
{
auto self(shared_from_this());
boost::asio::spawn(strand_,
[this, self, fbbP](boost::asio::yield_context yield)
{
try
{
boost::system::error_code ec;
// todo: check if error code no_buffer_space
socket_.async_send(boost::asio::buffer(fbbP->GetBufferPointer(), fbbP->GetSize()), yield[ec]);
}
catch (std::exception& e)
{
//socket_.close();
//timer_.cancel();
}
});
}
private:
// todo: may need to create io_service::work object here to keep io_service from exiting run() call
azmq::socket socket_;
boost::asio::io_service::strand strand_;
};
int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;
// Register signal handlers so that the daemon may be shut down when a signal is received.
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
signals.async_wait( std::bind(&boost::asio::io_service::stop, &io_service));
boost::system::error_code ec;
azmq::socket sendSocket(io_service, ZMQ_DEALER);
sendSocket.connect("tcp://127.0.0.1:9998");
auto sessionSharedP = std::make_shared<session>(std::move(sendSocket));
// Will run until signal is received
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment