Skip to content

Instantly share code, notes, and snippets.

@ymurase
Created November 15, 2014 08:07
Show Gist options
  • Save ymurase/647d793673634d2331c1 to your computer and use it in GitHub Desktop.
Save ymurase/647d793673634d2331c1 to your computer and use it in GitHub Desktop.
A sample of synchronous TCP client using boost::asio.
#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;
}
@zhangbolily
Copy link

同样出现到read这里就一直循环等待的情况,无解…………

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