Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_udpSock.cpp 1.9KB

6 månader sedan
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <csignal>
  11. #include <iostream>
  12. #include "Util/util.h"
  13. #include "Util/logger.h"
  14. #include "Network/Socket.h"
  15. using namespace std;
  16. using namespace toolkit;
  17. //主线程退出标志
  18. bool exitProgram = false;
  19. //赋值struct sockaddr
  20. void makeAddr(struct sockaddr_storage *out,const char *ip,uint16_t port){
  21. *out = SockUtil::make_sockaddr(ip, port);
  22. }
  23. //获取struct sockaddr的IP字符串
  24. string getIP(struct sockaddr *addr){
  25. return SockUtil::inet_ntoa(addr);
  26. }
  27. int main() {
  28. //设置程序退出信号处理函数
  29. signal(SIGINT, [](int){exitProgram = true;});
  30. //设置日志系统
  31. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  32. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  33. Socket::Ptr sockRecv = Socket::createSocket();//创建一个UDP数据接收端口
  34. Socket::Ptr sockSend = Socket::createSocket();//创建一个UDP数据发送端口
  35. sockRecv->bindUdpSock(9001);//接收UDP绑定9001端口
  36. sockSend->bindUdpSock(0, "0.0.0.0");//发送UDP随机端口
  37. sockRecv->setOnRead([](const Buffer::Ptr &buf, struct sockaddr *addr , int){
  38. //接收到数据回调
  39. DebugL << "recv data form " << getIP(addr) << ":" << buf->data();
  40. });
  41. struct sockaddr_storage addrDst;
  42. makeAddr(&addrDst,"127.0.0.1",9001);//UDP数据发送地址
  43. // sockSend->bindPeerAddr(&addrDst);
  44. int i = 0;
  45. while(!exitProgram){
  46. //每隔一秒往对方发送数据
  47. sockSend->send(to_string(i++), (struct sockaddr *)&addrDst);
  48. sleep(1);
  49. }
  50. return 0;
  51. }