asio 广播代码示例

代码网络收集 修改了一个编译的小问题

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Client.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <iostream>
 
#include <boost/asio.hpp>
 
int main()
{
    namespace ip = boost::asio::ip;
    boost::asio::io_service io_service;
 
    // Client binds to any address on port 8888 (the same port on which
    // broadcast data is sent from server).
    ip::udp::socket socket(io_service,
        ip::udp::endpoint(ip::udp::v4(), 8888));
 
    ip::udp::endpoint sender_endpoint;
 
    // Receive data.
    //boost::array<char, 4> buffer;
    char buf[500] = { 0 };
    std::size_t bytes_transferred =
        socket.receive_from(boost::asio::buffer(buf), sender_endpoint);
 
    std::cout << "got " << bytes_transferred << " bytes." <<  buf <<std::endl;
}

  服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Server.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <boost/asio.hpp>
 
int main()
{
    namespace ip = boost::asio::ip;
    boost::asio::io_service io_service;
 
    // Server binds to any address and any port.
    ip::udp::socket socket(io_service,
        ip::udp::endpoint(ip::udp::v4(), 0));
    socket.set_option(boost::asio::socket_base::broadcast(true));
 
    // Broadcast will go to port 8888.
    ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 8888);
 
    // Broadcast data.
    //boost::array<char, 4> buffer;
    char* buf = "测试代码";
    socket.send_to(boost::asio::buffer(buf,strlen(buf)+1), broadcast_endpoint);
}

  

posted on   itdef  阅读(554)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示