gpt4 book ai didi

C++ boost asio : bind: Address already in use

转载 作者:行者123 更新时间:2023-11-30 05:33:32 27 4
gpt4 key购买 nike

我正在使用 C++ boost asio 制作服务器客户端应用程序。

我遵循了 here 中的指南.

我仍然想知道为什么我会得到以下结果:

./server    #ok

./client # error

bind: Address already in use


服务器.cpp:

#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>
#include <boost/array.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

struct UDP_Message
{
double number;
};

int main()
{
try
{
boost::asio::io_service io_service;
udp::socket socket(io_service, udp::endpoint(udp::v4(), config::udp_port));
UDP_Message message;
message.number=0;
for (;;)
{
udp::endpoint remote_endpoint;
message.number=message.number+0.001;
boost::system::error_code ignored_error;
socket.send_to(boost::asio::buffer(&message,sizeof(message)),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}

客户端.cpp:

#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>
#include <boost/array.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

namespace config
{
const unsigned short udp_port=1414;
}

struct UDP_Message
{
double number;
};

int main()
{
try
{
boost::asio::io_service io_service;
boost::asio::socket_base::reuse_address option(true);
udp::socket socket(io_service, udp::v4());
socket.set_option(option);
socket.bind(udp::endpoint(udp::v4(), config::udp_port));
UDP_Message message;
for (;;)
{
boost::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
boost::system::error_code error;
socket.receive_from(boost::asio::buffer(recv_buf),
remote_endpoint, 0, error);
if (error && error != boost::asio::error::message_size)
throw boost::system::system_error(error);
std::memcpy(&message,recv_buf.data(),sizeof(message));
std::cout<<message.number<<std::endl;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}

最佳答案

您正在尝试将您的客户端和服务器绑定(bind)到同一个端口,udp_port=1414。这是你做不到的。

关于C++ boost asio : bind: Address already in use,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34746948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com