#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 ());//parse string into system command, then execute
Fin.open (outputFile);//exist open file, otherwise create
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) Gets the current time, CTime converts the time into a word
Character string. 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 (endpoint) consists of an IP address, a port number, and a protocol version.
(), 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 equivalent to a buffer of the monitor, a container for temporarily storing data
Boost::asio::transfer_all (), ignored_error); Self-feeling read and write are a fixed routine
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