0
我從boost文檔網站構建了簡單的boost應用程序,但仍然不知道如何使用它。Boost庫客戶端 - 服務器應用程序
1- Server application:
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
2 - 客戶端應用程序:
#include<iostream>
#include<exception>
#include "boost\array.hpp"
#include "boost\asio.hpp"
using namespace std;
using namespace boost;
using boost::asio::ip::tcp;
int main(int argc, char *argv[])
{
try
{
if (argc != 2)
{
cerr << "usage: client <host>" << endl;
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
asio::connect(socket, endpoint_iterator);
for (;;)
{
boost::array<char, 128> buf;
system::error_code error_code;
size_t len = socket.read_some(asio::buffer(buf), error_code);
if (error_code == asio::error::eof)
break; //Connection closed.
else
throw system::system_error(error_code);
cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
cerr << e.what() << endl;
}
while (true)
{
}
return 0;
}
那麼,接下來呢?
我exe然後客戶端,但沒有看到更多的Flash控制檯應用程序。 。
(注:這兩個應用程序編譯罰款,並與配置沒有問題
如果你喜歡看到控制檯輸出,在你的'while'循環結尾添加'std :: cin.get()'。 – Wum
@Wum Huh,什麼?我寧願打開兩個終端並運行服務器在一個客戶端和另一個客戶端 –
該服務器在成功連接之後僅向客戶端發送當前日期和時間,然後終止它。 lient _ do not_顯示消息並退出。 (參見@ DmitryBakhtiyarov的回答)沒有更多。 – user4407569