Created
May 30, 2017 12:34
-
-
Save rhulha/4f30c0d164a1d3ee20507a540fd41a1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _WIN32_WINNT 0x0601 | |
#ifdef _MSC_VER | |
#include <boost/config/compiler/visualc.hpp> | |
#endif | |
#include <cstdlib> | |
#include <iostream> | |
#include <string> | |
#include <boost/bind.hpp> | |
#include <boost/smart_ptr.hpp> | |
#include <boost/asio.hpp> | |
#include <boost/thread/thread.hpp> | |
#include <boost/iostreams/stream.hpp> | |
#include <boost/iostreams/concepts.hpp> | |
using boost::asio::ip::tcp; | |
typedef boost::shared_ptr<tcp::socket> socket_ptr; | |
// http://www.boost.org/doc/libs/1_64_0/libs/iostreams/doc/tutorial/container_source.html | |
class my_source : public boost::iostreams::source | |
{ | |
public: | |
my_source(socket_ptr sock) : _sock(sock) | |
{ | |
} | |
std::streamsize read(char* s, std::streamsize n) | |
{ | |
return _sock->read_some(boost::asio::buffer(s, n)); | |
} | |
private: | |
socket_ptr _sock; | |
}; | |
void session(socket_ptr sock) | |
{ | |
try { | |
std::string line; | |
boost::iostreams::stream<my_source> in(sock); | |
for (;;) { | |
std::getline(in, line); | |
if (line.length() > 0) | |
std::cout << line << std::endl; | |
else | |
break; | |
} | |
} | |
catch (std::exception& e) { | |
std::cerr << "Exception in thread: " << e.what() << "\n"; | |
} | |
} | |
void server(boost::asio::io_service& io_service, unsigned short port) | |
{ | |
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port)); | |
for (;;) { | |
socket_ptr sock(new tcp::socket(io_service)); | |
a.accept(*sock); | |
boost::thread t(boost::bind(session, sock)); | |
} | |
} | |
void runAsioReadLineServer() | |
{ | |
try { | |
boost::asio::io_service io_service; | |
server(io_service, 1212); | |
} | |
catch (std::exception& e) { | |
std::cerr << "Exception: " << e.what() << "\n"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment