gpt4 book ai didi

c++ - Boost::Asio 点对点 udp 聊天

转载 作者:行者123 更新时间:2023-12-04 14:21:41 27 4
gpt4 key购买 nike

我正在编写用于交换文本消息的点对点(它不应该有服务器 - 这是一项任务)程序。这是一个非常小的聊天。只是消息,没有别的。这是我第一次练习 Boost::Asio,因此我有一些问题。

正如我所说,我的聊天应该是点对点的,并且应该使用 udp 协议(protocol)。我认为,最好的方法是使用广播。第一个问题:我如何了解新的连接?

另一个问题是发送消息:我通过广播地址发送它,然后它传播到本地网络中的所有计算机。这样对吗?

此代码发送消息并接收其回复。就像一个回声。这样对吗?

#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>

int main()
{
try
{
namespace ip = boost::asio::ip;
boost::asio::io_service io_service;

ip::udp::socket socket(io_service,
ip::udp::endpoint(ip::udp::v4(), 1555));
socket.set_option(boost::asio::socket_base::broadcast(true));

ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 1555);

boost::array<char, 4> buffer1;
socket.send_to(boost::asio::buffer(buffer1), broadcast_endpoint);

ip::udp::endpoint sender_endpoint;

boost::array<char, 4> buffer2;
std::size_t bytes_transferred =
socket.receive_from(boost::asio::buffer(buffer2), sender_endpoint);

std::cout << "got " << bytes_transferred << " bytes." << std::endl;
}
catch (std::exception &e)
{
std::cerr << e.what();
}

system("PAUSE");

return 0;
}

最佳答案

我认为您应该尝试使用多播。我目前正在处理几乎相同的问题。

关于c++ - Boost::Asio 点对点 udp 聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23875010/

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