我是C ++ boost库的新手。我已经设法使用boost asio库实现UDP服务器和客户端。目前在我的示例程序中,我启动UDP服务器,然后尝试使用UDP客户端进行连接。一旦客户端连接并发送一些数据,服务器就会响应一个随机生成的字符串,我已将其转换为十六进制并将其打印出来。一旦收到字符串,UDP客户端就会调用destruct-or并退出。
我的代码在udp_server.hpp和udp_client.hpp
下面给出#include "udp_server.hpp"
#include <iostream>
#include <exception>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <sstream>
#include <iomanip>
const int ARG_COUNT = 2;
const int LOWEST_PORT = 1024;
const int HIGHEST_PORT = 65000;
static char message_array[8192];
void gen_random_string(char *s, const int len)
{
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service,int port_number)
: socket_(io_service, boost::asio::ip::udp::udp::endpoint(boost::asio::ip::udp::udp::v4(), port_number))
{
std::cout << "UDP server listening on " << port_number << std::endl;
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)
{
gen_random_string(message_array, 8192);
boost::shared_ptr<std::string> message(new std::string(message_array));
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*/)
{
}
boost::asio::ip::udp::udp::socket socket_;
boost::asio::ip::udp::udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
void runUDPServer( CmdLineOpts input )
{
try
{
boost::asio::io_service io_service;
udp_server server(io_service,input.port);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
class udp_client
{
public:
udp_client(
boost::asio::io_service& io_service,
const std::string& host,
const std::string& port
) : io_service_(io_service), socket_(io_service, boost::asio::ip::udp::udp::endpoint(boost::asio::ip::udp::udp::v4(), 0)) {
boost::asio::ip::udp::udp::resolver resolver(io_service_);
boost::asio::ip::udp::udp::resolver::query query(boost::asio::ip::udp::udp::v4(), host, port);
boost::asio::ip::udp::udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
}
~udp_client()
{
std::cout << "Calling UDP client destructor" << std::endl;
socket_.close();
}
void send() {
socket_.send_to(boost::asio::buffer(send_buf), endpoint_);
}
void recieve_from() {
/*Initialize our endpoint*/
boost::array<unsigned char, 8192> temp;
// boost::asio::buffer boost_buf(temp);
size_t len = socket_.receive_from(
boost::asio::buffer(temp), sender_endpoint);
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill( '0' );
std::for_each( temp.cbegin(), temp.cend(), [&]( int c ) { ss << std::setw( 2 ) << c; } );
std::string result = ss.str();
std::cout << "Length of recieved message " << len << std::endl;
std::cout << result << std::endl;
}
private:
boost::asio::io_service& io_service_;
boost::asio::ip::udp::udp::socket socket_;
boost::asio::ip::udp::udp::endpoint endpoint_;
//boost::array<char, 2048> recv_buf;
std::vector<unsigned char> recv_buf;
boost::array<char, 1> send_buf = {{ 0 }};
boost::asio::ip::udp::endpoint sender_endpoint;
};
void runUDPClient(std::string portStr)
{
try
{
boost::asio::io_service io_service;
udp_client client(io_service, "localhost", portStr);
client.send();
client.recieve_from();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void runClient( CmdLineOpts input )
{
runUDPClient(input.portStr);
}
void runServer( CmdLineOpts input )
{
runUDPServer(input);
}
/**
* Usage: client_server <protocol> <port> <num of packets>
*/
bool clarg_parse ( int argc, char *argv[], CmdLineOpts *input )
{
bool result = true;
if (argc - 1 == ARG_COUNT)
{
// arg 1: server or client
int arg1 = std::stoi(argv[1]);
if (arg1 == 0 || arg1 == 1)
{
input->servOrClient = arg1;
}
else
{
std::cout << "Invalid client server choice.\nUsage: client_server <client (0) or server(1)> <port>" << std::endl;
result = false;
}
// arg 2: port
int arg2 = std::stoi(argv[3]);
if (arg2 > LOWEST_PORT && arg2 < HIGHEST_PORT )
{
input->port = arg2;
input->portStr = argv[3];
}
else
{
std::cout << "Invalid port, must be between " << LOWEST_PORT << " and " << HIGHEST_PORT << std::endl;
std::cout << "Usage: client_server <client (0) or server(1)> <port>" << std::endl;
result = false;
}
}
else
{
std::cout << "Usage: client_server <client (0) or server(1)> <port>" << std::endl;
result = false;
}
return result;
}
int main ( int argc, char *argv[] )
{
CmdLineOpts input;
if (clarg_parse(argc, argv, &input))
{
if(input.servOrClient == 1)
{
runServer(input);
}
else if(input.servOrClient == 0)
{
runClient(input);
}
}
else
{
return 1;
}
return 0;
}
头文件udp_server.hpp
#ifndef UDP_SERVER_H_INCLUDED
#define UDP_SERVER_H_INCLUDED
#include <string>
struct CmdLineOpts
{
std::string portStr;
int port;
int servOrClient;
};
void runUDPServer ( CmdLineOpts input );
bool clarg_parse ( int argc, char *argv[], CmdLineOpts input );
#endif
Makefile编译上面的程序
TARGET = udp_server
LIBS = -lboost_system -lpthread
CXX = g++
CXXFLAGS = -std=c++11 -g -Wall -pedantic
.PHONY: default all clean
default: $(TARGET)
all: default
OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))
HEADERS = $(wildcard *.hpp)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
.PRECIOUS: $(TARGET) $(OBJECTS)
$(TARGET): $(OBJECTS)
$(CXX) $(OBJECTS) $(LIBS) -o $@
clean:
-rm -f *.o
-rm -f $(TARGET)
我的问题如下。
1)设计是否适合发送网络数据包。我担心的是,当客户端向服务器发送一些数据时,似乎发送了数据包(即服务器响应)。换句话说,客户端需要定期轮询服务器以查询数据。是否有其他模型服务器通知客户端数据可用?这会是一个更好的设计吗?
2)在示例中,我为客户端和服务器分配了一个8192字节的数组。这需要吗?据我所知,UDP的MTU(以及TCP为1500字节)。是否有任何理由在客户端和服务器上分配超过1500字节的数组。?
如果有人能够回答上述问题,那真的很棒。
答案 0 :(得分:1)
在为应用程序协议设计I / O层时,请考虑预期的网络拓扑,应用程序协议要求,任何服务级别协议,硬件要求等。围绕满足这些约束进行设计,而不是过多地投入精力优化效率低。在不了解更多细节的情况下,回答设计是好的还是其他设计更好是主观的。尽管如此:
对于给定的层,maximum transmission unit(MTU)定义可以向前传递到下一层的协议单元的最大大小。更高级别的层和协议可能会引入碎片处理,允许给定层的协议单元的最大大小超过较低层的MTU。例如,虽然以太网帧的MTU为1500字节,但UDP 数据报(第4层:传输)有效负载的最大大小为65507字节。这是可能的,因为IP层数据包(第3层:网络)可以由一个或多个以太网帧(第2层:数据链路)构成。
应该使用的缓冲区大小通常取决于应用程序协议。例如,Asio Chat example使用516字节的缓冲区,因为应用程序协议的最大长度为516字节。低层协议单元的分段和重组将对应用程序透明。但是,由于UDP既不提供确认也不提供重传,并且丢失部分数据报将导致整个数据报被丢弃,较大的数据报由于更大的碎片而更有可能丢失。