当前位置:   article > 正文

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

boost asio同步接收发送UDP数据包
  1. #include <boost/asio.hpp>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <iostream>
  5. #include <iostream>
  6. #define SERVER
  7. enum { max_length = 1024 };
  8. using namespace std;
  9. using namespace boost;
  10. using boost::asio::ip::udp;
  11. int main(int argc, char** argv) {
  12. try {
  13. #ifdef SERVER
  14. cout << "server start ……" << endl;
  15. asio::io_context io;
  16. auto serPointn=udp::endpoint(udp::v4(), 6688);
  17. udp::socket sock(io, serPointn);
  18. char buf[0xFF];
  19. udp::endpoint cliPoint;
  20. while (1) {
  21. sock.receive_from(asio::buffer(buf), cliPoint);
  22. sock.send_to(asio::buffer(buf), cliPoint);
  23. }
  24. #else
  25. asio::io_context io;
  26. udp::socket sock(io);
  27. sock.open(asio::ip::udp::v4());
  28. udp::endpoint serPoint=udp::endpoint(asio::ip::address::from_string("127.0.0.1"), 6688);
  29. while (1) {
  30. char buf[0xFF];
  31. cin >> buf;
  32. sock.send_to(asio::buffer(buf), serPoint);
  33. memset(buf, 0, 0xFF);
  34. sock.receive_from(asio::buffer(buf), serPoint);
  35. cout << buf << endl;
  36. }
  37. ::system("pause");
  38. #endif //
  39. }
  40. catch (std::exception& e) {
  41. std::cerr << "Exception" << e.what() << "\n";
  42. }
  43. return 0;
  44. }

异步

  1. #include<iostream>
  2. #include"boost/asio.hpp"
  3. #include"boost/bind.hpp"
  4. using namespace std;
  5. using namespace boost;
  6. using asio::ip::udp;
  7. void sock_recv(char* buf, udp::socket* sock, udp::endpoint* cliPoint);
  8. void sock_send(char* buf, udp::socket* sock, udp::endpoint* cliPoint);
  9. int main() {
  10. cout << "server start ……" << endl;
  11. asio::io_context io;
  12. udp::socket *sock=new udp::socket(io, udp::endpoint(udp::v4(), 6688));
  13. char *buf=new char[0xFF];
  14. udp::endpoint *cliPoint=new udp::endpoint;
  15. sock->async_receive_from(asio::buffer(buf,0xFF),*cliPoint,
  16. boost::bind(sock_recv,buf,sock,cliPoint));
  17. io.run();
  18. }
  19. void sock_send(char* buf, udp::socket* sock, udp::endpoint* cliPoint) {
  20. try
  21. {
  22. sock->async_receive_from(asio::buffer(buf, 0xFF), *cliPoint,
  23. boost::bind(sock_recv, buf, sock, cliPoint));
  24. }
  25. catch (const std::exception& e)
  26. {
  27. cout << e.what();
  28. }
  29. }
  30. void sock_recv(char* buf, udp::socket* sock, udp::endpoint* cliPoint) {
  31. try
  32. {
  33. sock->async_send_to(asio::buffer(buf, 0xFF), *cliPoint,
  34. boost::bind(sock_send, buf, sock, cliPoint));
  35. }
  36. catch (const std::exception& e)
  37. {
  38. cout << e.what();
  39. }
  40. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/406315
推荐阅读
相关标签
  

闽ICP备14008679号