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();
}
}