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