Skip to content

Instantly share code, notes, and snippets.

@moccos
Last active August 29, 2015 14:09
Show Gist options
  • Save moccos/dd7396e4a009cff25f41 to your computer and use it in GitHub Desktop.
Save moccos/dd7396e4a009cff25f41 to your computer and use it in GitHub Desktop.
boost asio TCP server snippet. All resources will leak.
#include <stdio.h>
#include <string.h>
#include <memory>
#include <boost/asio.hpp>
static const int PORT = 23455;
static const int BUF_SIZE = 1024 * 4;
static const int UNIT_SIZE = 8;
using namespace boost::asio;
io_service service;
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), PORT);
ip::tcp::socket sock(service);
ip::tcp::acceptor acc(service, ep);
ip::tcp::socket *p_sock = nullptr;
char buf[BUF_SIZE];
void handle_read(const boost::system::error_code &err, size_t nread) {
if (err) {
printf("handle_read error! %d\n", (int)nread);
return;
}
printf("handle_read: (%d) ", (int)nread);
for (size_t i = 0; i < nread; i++) {
printf("%02x ", buf[i]);
}
printf("\n");
p_sock->async_read_some(buffer(buf, UNIT_SIZE), handle_read);
//async_read(*p_sock, buffer(buf, UNIT_SIZE), handle_read);
}
void handle_accept(const boost::system::error_code &err) {
if (err) {
printf("handle_accept error!\n");
return;
}
printf("handle_accept\n");
p_sock->async_read_some(buffer(buf, UNIT_SIZE), handle_read);
//async_read(*p_sock, buffer(buf, UNIT_SIZE), handle_read);
}
int main(int argc, char **argv) {
std::memset(buf, 0, BUF_SIZE);
acc.set_option(ip::tcp::socket::reuse_address(true));
p_sock = new ip::tcp::socket(service);
acc.async_accept(*p_sock, handle_accept);
printf("service.run: port %d\n", PORT);
service.run();
printf("exit program.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment