一、server 端
-
创建udp::socket,用于收发数据
1)需要创建一个io_context对象,初始化socket对象
2)创建一个udp::endpoint对象,指定协议版本(v4,v6)和端口号,初始化socket对象 -
执行收发动作,socket.receive_from和socket.send_to
1)收发都需要一个asio::buffer缓存。
2)receive_from可以获取到client的endpoint,也可以用这个对象给client发送数据(send_to)
二、client 端
- 创建一个udp::socket对象,用于收发数据。
- 使用socket对象收发数据,socket.send_to和receive_from
1)创建一个udp::endpoint对象,指定server端地址、端口。
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
using namespace std;
using namespace boost;
using namespace boost::asio;
using asio::ip::udp;
void server_func() {
io_context io;
udp::socket server_socket(io, udp::endpoint(udp::v4(), 22333));
int count = 1;
while(true) {
char buf[128] = {0};
udp::endpoint client_endpoint;
server_socket.receive_from(asio::buffer(buf), client_endpoint);
printf("server -> [%d]: %s\n", count++, buf);
cout << "server -> client info: " << client_endpoint.address() << ":" << client_endpoint.port() << endl;
server_socket.send_to(asio::buffer("received from server"), client_endpoint);
}
}
void client_func() {
io_context io;
udp::socket client_socket(io, udp::v4());
udp::endpoint server_endpoint(ip::address::from_string("127.0.0.1"), 22333);
while(true) {
char buf[128] = {0};
cout << "client -> input:\n";
cin >> buf;
client_socket.send_to(asio::buffer(buf), server_endpoint);
// cout << "client -> get feedback from server: " << server_endpoint.address() << ":" << server_endpoint.port() << endl;
// bzero(buf, 128);
client_socket.receive_from(asio::buffer(buf), server_endpoint);
// cout << "client -> " << buf << endl;
}
}
int main() {
jthread server(server_func);
cout << "start server\n";
jthread client(client_func);
cout << "start client\n";
return 0;
}