本文主要是介绍简单使用asio发送组播包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说明
直接使用asio库来发送,这样比较简单
show me the code
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>// 3rd party includes.
#include <asio.hpp>
#include <string>using asio::ip::udp;class c_multisock
{
public:c_multisock():v_socket(v_service){}void read(){asio::ip::udp::endpoint sender;std::vector<char> buffer;std::size_t bytes_readable = 0;asio::socket_base::bytes_readable num_of_bytes_readable(true);v_socket.io_control(num_of_bytes_readable);// Get the value from the command.bytes_readable = num_of_bytes_readable.get();// If there is no data available, then sleep.if (!bytes_readable){return;}// Resize the buffer to store all available data.buffer.resize(bytes_readable);// Read available data.v_socket.receive_from(asio::buffer(buffer, bytes_readable),sender);// Extract data from the buffer.std::string message(buffer.begin(), buffer.end());// Output data.std::cout << "Received message: ";std::cout << message << std::endl;}void write(uint8_t *data, size_t len){//char buffer[256];//sprintf(buffer, msearchmsgfmt, "upnp:rootdevice");/*socket.async_send_to(boost::asio::buffer(buffer, strlen(buffer)), endpoint_,boost::bind(handle_send_to, this,boost::asio::placeholders::error));*/v_socket.send_to(asio::buffer(data, len), v_destination);}int asio_init(const char * ip,uint16_t port, bool receiver){asio::ip::address address =asio::ip::address::from_string(ip); //"239.255.255.250"//udp::socket socket(v_service);v_socket.open(asio::ip::udp::v4());// Allow other processes to reuse the address, permitting other processes on// the same machine to use the multicast address.v_socket.set_option(udp::socket::reuse_address(true));// Guarantee the loopback is enabled so that multiple processes on the same// machine can receive data that originates from the same socket.v_socket.set_option(asio::ip::multicast::enable_loopback(true));v_receiver = receiver;v_socket.bind(udp::endpoint(asio::ip::address_v4::any(),receiver ? port /* same as multicast port */: 16200/* any */));v_destination = udp::endpoint(address, port);// Join group.v_socket.set_option(asio::ip::multicast::join_group(address));// Start read or write loops based on command line options.//if (receiver) read(socket);//else write(socket, destination);return 0;}
private:bool v_receiver;udp::endpoint v_destination;asio::io_context v_service;udp::socket v_socket;
};
这篇关于简单使用asio发送组播包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!