Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sh19910711
Created March 10, 2013 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sh19910711/5127130 to your computer and use it in GitHub Desktop.
Save sh19910711/5127130 to your computer and use it in GitHub Desktop.
UNIX-domain socketsを使ってClient/Serverする例
// compile: g++ -lboost_system client.cpp
#include <iostream>
#include <boost/asio.hpp>
const std::string SOCKET_NAME = "/tmp/socket";
int main(){
boost::asio::io_service io_service;
boost::asio::local::stream_protocol::socket socket(io_service);
boost::asio::local::stream_protocol::endpoint ep(SOCKET_NAME);
socket.connect(ep);
std::string line;
while ( std::getline( std::cin, line ) ) {
boost::system::error_code error;
if ( 0 == boost::asio::write( socket, boost::asio::buffer(line), error ) )
break;
if ( error ) {
std::cerr << error.message() << std::endl;
} else {
std::cout << "send ok: " << line << std::endl;
}
}
return 0;
}
#include <iostream>
#include <boost/asio.hpp>
const std::string SOCKET_NAME = "/tmp/socket";
int main() {
::unlink(SOCKET_NAME.c_str());
boost::asio::io_service io_service;
boost::asio::local::stream_protocol::endpoint ep(SOCKET_NAME);
boost::asio::local::stream_protocol::acceptor acceptor(io_service, ep);
boost::asio::local::stream_protocol::socket socket(io_service);
acceptor.accept(socket);
for (;;) {
boost::asio::streambuf buffer;
boost::system::error_code error;
if ( 0 == boost::asio::read( socket, buffer, boost::asio::transfer_at_least(1), error ) )
break;
if ( error && error != boost::asio::error::eof ) {
std::cerr << "error: " << error.message() << std::endl;
} else {
std::string data(boost::asio::buffer_cast<const char*>(buffer.data()));
std::cout << "message: " << data << std::endl;
if ( data == "quit" )
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment