Created
November 15, 2014 08:08
-
-
Save ymurase/7f602adda5cb095fb530 to your computer and use it in GitHub Desktop.
A sample of synchronous TCP server using boost::asio
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
#include <iostream> | |
#include <boost/asio.hpp> | |
namespace asio = boost::asio; | |
std::string readline( asio::ip::tcp::socket & socket ) { | |
asio::streambuf buf; | |
asio::read_until( socket, buf, "\n" ); | |
std::string data = asio::buffer_cast<const char*>(buf.data()); | |
data.erase( --data.end() ); // remove the last delimeter | |
return data; | |
} | |
void sendline( asio::ip::tcp::socket & socket, const std::string& str ) { | |
const std::string msg = str + "\n"; | |
asio::write( socket, asio::buffer(msg) ); | |
} | |
int main() { | |
asio::io_service io_service; | |
asio::ip::tcp::acceptor acc( | |
io_service, | |
asio::ip::tcp::endpoint( asio::ip::tcp::v4(), 31400 ) ); | |
asio::ip::tcp::socket socket(io_service); | |
acc.accept( socket ); | |
while(true) { | |
std::string str = readline( socket ); | |
std::cout << str << std::endl; | |
sendline(socket, "pong"); | |
std::cout << "sent pong" << std::endl; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment