boost asio同步接收发送UDP数据包

cpp 复制代码
#include <boost/asio.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <iostream>

#define SERVER

enum { max_length = 1024 };
using namespace std;
using namespace boost;
using boost::asio::ip::udp;

int main(int argc, char** argv) {

	try {
#ifdef SERVER
		cout << "server start ......" << endl;
		asio::io_context io;
		auto serPointn=udp::endpoint(udp::v4(), 6688);
		udp::socket sock(io, serPointn);

		char buf[0xFF];
		udp::endpoint cliPoint;
		while (1) {
			sock.receive_from(asio::buffer(buf), cliPoint);
			sock.send_to(asio::buffer(buf), cliPoint);
		}
#else
		asio::io_context io;
		udp::socket sock(io);
		sock.open(asio::ip::udp::v4());

		udp::endpoint serPoint=udp::endpoint(asio::ip::address::from_string("127.0.0.1"), 6688);

		while (1) {
			char buf[0xFF];
			cin >> buf;
			sock.send_to(asio::buffer(buf), serPoint);
			memset(buf, 0, 0xFF);
			sock.receive_from(asio::buffer(buf), serPoint);
			cout << buf << endl;
		}
		::system("pause");
#endif // 
	}
	catch (std::exception& e) {
		std::cerr << "Exception" << e.what() << "\n";
	}
	return 0;
}

异步

cpp 复制代码
#include<iostream>
#include"boost/asio.hpp"
#include"boost/bind.hpp"
using namespace std;
using namespace boost;
using asio::ip::udp;

void sock_recv(char* buf, udp::socket* sock, udp::endpoint* cliPoint);
void sock_send(char* buf, udp::socket* sock, udp::endpoint* cliPoint);


int main() {
	cout << "server start ......" << endl;
	asio::io_context io;
	
	udp::socket *sock=new udp::socket(io, udp::endpoint(udp::v4(), 6688));

	char *buf=new char[0xFF];
	udp::endpoint *cliPoint=new udp::endpoint;

	sock->async_receive_from(asio::buffer(buf,0xFF),*cliPoint,
boost::bind(sock_recv,buf,sock,cliPoint));

	io.run();

}


void sock_send(char* buf, udp::socket* sock, udp::endpoint* cliPoint) {
	try
	{
		sock->async_receive_from(asio::buffer(buf, 0xFF), *cliPoint, 
boost::bind(sock_recv, buf, sock, cliPoint));
	}
	catch (const std::exception& e)
	{
		cout << e.what();
	}
	
}

void sock_recv(char* buf, udp::socket* sock, udp::endpoint* cliPoint) {
	try
	{
		sock->async_send_to(asio::buffer(buf, 0xFF), *cliPoint, 
boost::bind(sock_send, buf, sock, cliPoint));

	}
	catch (const std::exception& e)
	{
		cout << e.what();
	}
}
相关推荐
肆忆_14 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星18 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc4 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼5 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛