network.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /*
  2. * network.h
  3. *
  4. * Created on: 2022年1月17日
  5. * Author: pengzc
  6. */
  7. #ifndef JNI_BASE_NETWORK_H_
  8. #define JNI_BASE_NETWORK_H_
  9. #include <stdint.h>
  10. #include <string>
  11. #include <netinet/in.h>
  12. namespace base {
  13. enum SocketConstant {
  14. SOCKET_SUCCESS = 0,
  15. SOCKET_ERROR = -1,
  16. SOCKET_TIMEOUT = -10001,
  17. SOCKET_INVALID = -10002,
  18. SOCKET_GET_ADDRESS_INFO = -10003,
  19. };
  20. class InetAddress {
  21. public:
  22. InetAddress();
  23. InetAddress(const std::string& host, int port);
  24. std::string ipv4() const;
  25. private:
  26. private:
  27. friend class DatagramSocket;
  28. friend class Socket;
  29. friend class ServerSocket;
  30. struct sockaddr_in address_;
  31. };
  32. class Socket {
  33. public:
  34. Socket();
  35. virtual ~Socket();
  36. /**
  37. * 0 成功,非0失败
  38. */
  39. int Connect(const std::string &host, int port, int timeout_millis);
  40. /**
  41. * >0 已发送的字节数
  42. * <=0 失败
  43. */
  44. int Write(uint8_t* data, int data_len);
  45. /**
  46. * < 0 失败
  47. * 0 已关闭
  48. * > 0 读取的字节数
  49. */
  50. int Read(uint8_t* buffer, int buffer_len, int timeout_millis);
  51. /**
  52. * 不再使用后,必须主动关闭,释放资源
  53. */
  54. int Close();
  55. /**
  56. * 对方网络地址
  57. */
  58. InetAddress inet_address() const;
  59. private:
  60. friend class ServerSocket;
  61. int socket_;
  62. InetAddress address_;
  63. };
  64. class ServerSocket {
  65. public:
  66. explicit ServerSocket(int port);
  67. virtual ~ServerSocket();
  68. /**
  69. * 阻塞,等待客户端连接
  70. * >=0 有客户端连接
  71. * < 0 出错
  72. */
  73. int Accept(Socket* socket);
  74. private:
  75. int server_socket_;
  76. struct sockaddr_in server_addr_;
  77. };
  78. class DatagramSocket {
  79. public:
  80. DatagramSocket();
  81. DatagramSocket(int port);
  82. virtual ~DatagramSocket();
  83. int SendTo(const InetAddress& address, const uint8_t* data, int len);
  84. int Receive(InetAddress* address, uint8_t* buffer, int buffer_length,
  85. int timeout_millis);
  86. /**
  87. * 不再使用后,必须主动关闭,释放资源
  88. */
  89. int Close();
  90. private:
  91. int socket_;
  92. };
  93. } /* namespace base */
  94. #endif /* JNI_BASE_NETWORK_H_ */