我试图让 daytime6 服务器示例(异步 UDP 白天服务器)在 boost 工作。我使用
编译下面的程序g++ -std=c++11 -g -Wall -pedantic udp_server.cpp -o udp_server -lboost_system
我启动了 udp_server
。我可以看到正在使用 netstat 命令打开端口号 13 (UDP)。
但是,如果我尝试使用 netcat 连接到服务器
nc -u localhost 13
它似乎没有给出任何回复。但是我可以让异步 TCP 白天服务器正常工作。
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error || error == boost::asio::error::message_size)
{
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string> message,
const boost::system::error_code& error,
std::size_t bytes_transferred)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
udp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
最佳答案
以下命令不发送消息:
$ nc -u localhost 13
相反,netcat 将等待,从标准输入读取直到文件结束。收到文件结尾后,它将使用 UDP 将读取的消息发送到端口 13 上的本地主机。
另一方面,以下命令:
$ echo 'msg' | nc -u localhost 13
将“msg”和文件结尾写入 netcat 的标准输入,导致 netcat 将包含“msg”的 UDP 数据报发送到端口 13 上的本地主机。
asynchronous UDP daytime server示例以当前日期和时间响应它收到的任何消息:
class udp_server
{
public:
udp_server(...)
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(...,
boost::bind(&udp_server::handle_receive, ...));
}
void handle_receive(...)
{
message = make_daytime_string();
socket_.async_send_to(boost::asio::buffer(message), ...);
}
};
由于第一个命令不写入消息,udp_server
永远不会收到它可以响应的消息。后一个命令导致写入一条消息,udp_server
以日期和时间响应。
asynchronous TCP daytime server在接受连接时写一条消息,然后关闭连接。使用 TCP 时,netcat 将尝试立即连接到目的地。在 tcp_server
的情况下,netcat 将建立 TCP 连接,接收日期和时间,检测到远程对等点已关闭连接并退出。
关于c++ - boost daytime7 服务器示例不响应 netcat 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492181/