码迷,mamicode.com
首页 > 其他好文 > 详细

tcp_sync_server and tcp_sync_client

时间:2015-04-12 22:29:02      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>

#include <fstream>

#include <sstream>

#include <boost/asio.hpp>

using namespace std;

 

using boost::asio::ip::tcp;

const char* serviceList =  "\n\t       Services\n"      

"\t**************************\n"

     "\t[1] Get current time.\n"

     "\t[2] Who‘s online.\n"

     "\t[3] Get system info.\n"

     "\t**************************\n\n"

     "Please pick a service[1-3]: ";

 

ifstream fin;

void getResult(const string& cmdPrefix, const char* outputFile,

string& res) {

    // cmd == "w > who"

    string cmd(cmdPrefix + outputFile);

    system(cmd.c_str());//将字符串解析为系统命令,然后执行      

      fin.open(outputFile);//存在打开文件,否则创建             

 if (fin) {  ostringstream os; os << fin.rdbuf(); res = os.str();   

 }

   

if (fin.is_open()) { fin.close();     }

}

 

string getServiceContent(const int& select) {

    string res;

    switch (select) { //time(0)获取当前时间,ctime将时间转换成字

符串。      case 1: {    time_t t = time(0); res = ctime(&t);  break;   

 }      case 2: getResult("w > ", "who", res);    break;   case 3: getResult("uname -a > ", "uname", res); break;      

default:  res = "Sorry, no such service.\n";  break;     }

   

return res; }              

int main() {     try {   boost::asio::io_service io_service; // #1  

       tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4     //tcp::endpoint(端点)由ip地址,端口号,协议版本组成。

(), 8868)); // #2    for (;;) {   tcp::socket socket(io_service); // #3              

acceptor.accept(socket); // #4

            // 1, send service list to client

boost::system::error_code ignored_error;            

boost::asio::write(socket, boost::asio::buffer(serviceList),     //buffer相当于显示器的一个缓冲,临时存储数据的一个容器

      boost::asio::transfer_all(), ignored_error);  //自我感觉read和write是一个固定套路

            // 2, receive selection from client              char selection[20];

size_t n = socket.read_some(boost::asio::buffer(selection),      

              ignored_error);             // 3, send response            

string response = getServiceContent(atoi(selection));            

boost::asio::write(socket, boost::asio::buffer(response),        

            boost::asio::transfer_all(), ignored_error);        

} // #6     } catch (std::exception& e) {

        std::cerr << e.what() << std::endl;     }

    return 0; }

tcp_sync_server and tcp_sync_client

标签:

原文地址:http://www.cnblogs.com/defen/p/4420617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!