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();
	}
}
相关推荐
岁忧1 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
蜉蝣之翼❉6 小时前
CRT 不同会导致 fopen 地址不同
c++·mfc
aramae7 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lixzest7 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
_Chipen8 小时前
C++基础问题
开发语言·c++
灿烂阳光g8 小时前
OpenGL 2. 着色器
c++·opengl
AA陈超9 小时前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻
mit6.82410 小时前
[Meetily后端框架] AI摘要结构化 | `SummaryResponse`模型 | Pydantic库 | vs marshmallow库
c++·人工智能·后端
R-G-B10 小时前
【02】MFC入门到精通——MFC 手动添加创建新的对话框模板
c++·mfc·mfc 手动添加创建新的对话框
linux kernel10 小时前
第七讲:C++中的string类
开发语言·c++