Created
November 15, 2014 08:07
-
-
Save ymurase/647d793673634d2331c1 to your computer and use it in GitHub Desktop.
A sample of synchronous TCP client 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; | |
int main() { | |
asio::io_service io_service; | |
asio::ip::tcp::socket socket(io_service); | |
socket.connect( asio::ip::tcp::endpoint( asio::ip::address::from_string("127.0.0.1"), 31400 ) ); | |
const std::string msg = "ping\n"; | |
boost::system::error_code error; | |
asio::write( socket, asio::buffer(msg), error ); | |
if( error ) { | |
std::cout << "send failed: " << error.message() << std::endl; | |
} | |
else { | |
std::cout << "send correct!" << std::endl; | |
} | |
asio::streambuf receive_buffer; | |
asio::read( socket, receive_buffer, asio::transfer_all(), error ); | |
if( error && error != asio::error::eof ) { | |
std::cout << "receive failed: " << error.message() << std::endl; | |
} | |
else { | |
const char* data = asio::buffer_cast<const char*>(receive_buffer.data()); | |
std::cout << data << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
同样出现到read这里就一直循环等待的情况,无解…………