You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9KB

  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. }