Advertisement
zhangsongcui

First Socket Program

Nov 4th, 2011
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <boost/asio.hpp>
  3. #include <boost/algorithm/string/compare.hpp>
  4. #include <boost/lexical_cast.hpp>
  5.  
  6. int main(int argc, const char* argv[])
  7. {
  8.     using boost::asio::ip::tcp;
  9.     enum { PORT = 12580 };
  10.     if ( argc == 2 && boost::is_iequal()(argv[1], (const char*)"server") == 0 )
  11.     {
  12.         boost::asio::io_service io_service;
  13.         tcp::endpoint endpoint( tcp::v4(), PORT );
  14.         tcp::acceptor acceptor( io_service, endpoint );
  15.        
  16.         tcp::iostream stream;
  17.         boost::system::error_code ec;
  18.         for (;;)
  19.         {
  20.             acceptor.accept( *stream.rdbuf(), ec );
  21.             if (!ec)
  22.                 std::cout << stream.rdbuf();
  23.             else
  24.             {
  25.                 std::cerr << "链接已中断:" << stream.error().message() << std::endl;
  26.                 return 0;
  27.             }
  28.         }
  29.     }
  30.     else if ( argc == 3 && boost::is_iequal()(argv[1], (const char*)"client") == 0 )
  31.     {
  32.         tcp::iostream stream( argv[2], boost::lexical_cast<std::string>(PORT) );
  33.         if (!stream)
  34.         {
  35.             std::cerr << "链接失败:" << stream.error().message() << std::endl;
  36.             return 1;
  37.         }
  38.  
  39.         std::string line;
  40.         for (;;)
  41.         {
  42.             std::getline(std::cin, line);
  43.             stream << line << std::endl;
  44.         }
  45.     }
  46.     else
  47.     {
  48.         std::cerr << "用法:\n\t"<< argv[0] << " server / client <host>" << std::endl;
  49.         return 1;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement