我正在尝试使用boost创建一个Client类(UDP)。我正在尝试将short udp client tutorial转换为可以处理连接的类。我对网络编程,提升或捕获错误不是很熟悉。我希望得到一个解决问题的答案
我找到了一个有用的TCPClient Question,但是一些差异(我甚至没有尝试做异步客户端/服务器)使它对我的问题无益。
以下是代码:
class Client {
private:
boost::asio::io_service* io;
udp::resolver* res;
udp::endpoint ep;
std::string ip;
udp::socket* sock;
boost::system::error_code err;
public:
Client(boost::asio::io_service& IO, std::string IP, std::string msg) : io(&IO) , ip(IP) ,
res(new udp::resolver(IO)) , sock(new udp::socket(IO)) {
udp::resolver::query qry(udp::v4(), IP, msg);
udp::resolver::iterator epit;
ep = *res->resolve(qry); //unhandled exception here
}
~Client() {
delete res; delete sock;
}
void Send(std::string & sbuf) {
sock->open(udp::v4());
sock->send_to(boost::asio::buffer(sbuf), ep);
}
void Listen() {
std::array<char,128> rbuf;
udp::endpoint sender_ep;
size_t len = sock->receive_from(boost::asio::buffer(rbuf), sender_ep);
std::cout.write(rbuf.data(),len);
}
};
程序失败在构造函数中收到未处理的异常(如注释)。确切的错误是
Unhandled exception at at 0x74C6C41F in Client.exe: Microsoft C++ exception:
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<
boost::system::system_error> > at memory location 0x0022F278.
主程序是
int main() {
boost::asio::io_service io;
boost::system::error_code MyErr;
Client Me(io,"127.0.0.1","MARCO");
std::string msg = "MARCO";
Me.Send(msg);
Me.Listen();
return 0;
}
我已经编写并在另一个程序中运行服务器类。我认为这是正确设置的,但也许它是问题的一部分
#include <iostream>
#include <thread>
#include <array>
#include <boost\asio.hpp>
#include <string>
using boost::asio::ip::udp;
class Server {
private:
boost::asio::io_service* io;
udp::socket* sock;
unsigned short port;
std::array<char,1> rbuf;
udp::endpoint rmtEP;
boost::system::error_code err, ierr;
public:
Server(boost::asio::io_service& IO, unsigned short PORT) : io(&IO) ,
sock(new udp::socket(IO, udp::endpoint(udp::v4(), PORT))) {}
~Server() { delete sock; }
void Listen() {
sock->receive_from(boost::asio::buffer(rbuf), rmtEP, 0, err);
if(err && err != boost::asio::error::message_size)
throw boost::system::system_error(err);
sock->send_to(boost::asio::buffer("POLO"), rmtEP, 0, ierr);
}
};
int main() {
boost::asio::io_service io;
boost::system::error_code MyErr;
Server Host(io, 13);
try{
Host.Listen();
}catch(std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
答案 0 :(得分:1)
不应低于
客户我(io,“127.0.0.1”,“MARCO”);
是
Client Me(io,"127.0.0.1","DAYTIME");
因为您要将msg传递给查询,并且该参数实际上应该是服务名称而不是您要发送的邮件。
您也可以从boost daytime tutorial看到
udp::resolver::query query(udp::v4(), argv[1], "daytime");