/* * network.h * * Created on: 2022年1月17日 * Author: pengzc */ #ifndef JNI_BASE_NETWORK_H_ #define JNI_BASE_NETWORK_H_ #include #include #include namespace base { enum SocketConstant { SOCKET_SUCCESS = 0, SOCKET_ERROR = -1, SOCKET_TIMEOUT = -10001, SOCKET_INVALID = -10002, SOCKET_GET_ADDRESS_INFO = -10003, }; class InetAddress { public: InetAddress(); InetAddress(const std::string& host, int port); std::string ipv4() const; private: private: friend class DatagramSocket; friend class Socket; friend class ServerSocket; struct sockaddr_in address_; }; class Socket { public: Socket(); virtual ~Socket(); /** * 0 成功,非0失败 */ int Connect(const std::string &host, int port, int timeout_millis); /** * >0 已发送的字节数 * <=0 失败 */ int Write(uint8_t* data, int data_len); /** * < 0 失败 * 0 已关闭 * > 0 读取的字节数 */ int Read(uint8_t* buffer, int buffer_len, int timeout_millis); /** * 不再使用后,必须主动关闭,释放资源 */ int Close(); /** * 对方网络地址 */ InetAddress inet_address() const; private: friend class ServerSocket; int socket_; InetAddress address_; }; class ServerSocket { public: explicit ServerSocket(int port); virtual ~ServerSocket(); /** * 阻塞,等待客户端连接 * >=0 有客户端连接 * < 0 出错 */ int Accept(Socket* socket); private: int server_socket_; struct sockaddr_in server_addr_; }; class DatagramSocket { public: DatagramSocket(); DatagramSocket(int port); virtual ~DatagramSocket(); int SendTo(const InetAddress& address, const uint8_t* data, int len); int Receive(InetAddress* address, uint8_t* buffer, int buffer_length, int timeout_millis); /** * 不再使用后,必须主动关闭,释放资源 */ int Close(); private: int socket_; }; } /* namespace base */ #endif /* JNI_BASE_NETWORK_H_ */