Skip to content

Instantly share code, notes, and snippets.

@spaghetti-
Created March 25, 2017 08:19
Show Gist options
  • Save spaghetti-/ca0c96237e7adef288d8cdc3a5ba5074 to your computer and use it in GitHub Desktop.
Save spaghetti-/ca0c96237e7adef288d8cdc3a5ba5074 to your computer and use it in GitHub Desktop.
Boost asio tcp server example, C++11
#include <iostream>
#include <memory>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
//thanks kalven for tips/debugging
using boost::asio::ip::tcp;
class Session : public std::enable_shared_from_this<Session>
{
public:
Session(boost::asio::io_service& ios)
: socket(ios) {}
tcp::socket& get_socket()
{
return socket;
}
void start()
{
socket.async_read_some(
boost::asio::buffer(data, max_length),
boost::bind(&Session::handle_read, this,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(std::shared_ptr<Session>& s,
const boost::system::error_code& err,
size_t bytes_transferred)
{
if (!err) {
std::cout << "recv: " + test << std::endl;
socket.async_read_some(
boost::asio::buffer(data, max_length),
boost::bind(&Session::handle_read, this,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
} else {
std::cerr << "err (recv): " << err.message() << std::endl;
}
}
private:
tcp::socket socket;
enum { max_length = 1024 };
char data[max_length];
};
class Server {
public:
Server(boost::asio::io_service& ios,
short port) : ios(ios), acceptor(ios, tcp::endpoint(tcp::v4(), port))
{
std::shared_ptr<Session> session = std::make_shared<Session>(ios);
acceptor.async_accept(session->get_socket(),
boost::bind(&Server::handle_accept, this,
session,
boost::asio::placeholders::error));
}
void handle_accept(std::shared_ptr<Session> session,
const boost::system::error_code& err)
{
if (!err) {
session->start();
session = std::make_shared<Session>(ios);
acceptor.async_accept(session->get_socket(),
boost::bind(&Server::handle_accept, this, session,
boost::asio::placeholders::error));
}
else {
std::cerr << "err: " + err.message() << std::endl;
session.reset();
}
}
private:
boost::asio::io_service& ios;
tcp::acceptor acceptor;
};
int main(int argc, char *argv[])
{
try {
boost::asio::io_service ios;
Server s(ios, 8080);
ios.run();
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
@NoahMarple
Copy link

NoahMarple commented Aug 1, 2021

good question
only 1 reference, fails to compile, compiles broken when removed

@spaghetti-
Copy link
Author

Well, this was written 4 years ago so I'm not really sure what I was doing with test here, but you can just remove it. Compiles with warnings when removed: https://wandbox.org/permlink/yNAo9pw7HQQCeMDO

I haven't done cpp in a long time so I don't recommend using this without fixing all the warnings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment