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();
	}
}
相关推荐
苏比的博客28 分钟前
Windows MFC添加类,变量,类导向
c++·windows·mfc
yudiandian201435 分钟前
MFC - 使用 Base64 对图片进行加密解密
c++·mfc
yudiandian201436 分钟前
MFC - Picture Control 控件显示图片
c++·mfc
我是李武涯6 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
卡提西亚6 小时前
C++笔记-10-循环语句
c++·笔记·算法
亮剑20187 小时前
第1节:C语言初体验——环境、结构与基本数据类型
c++
William_wL_7 小时前
【C++】类和对象(下)
c++
William_wL_8 小时前
【C++】内存管理
c++
星星火柴9368 小时前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习
悲伤小伞9 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp