1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| #pragma once
#include <cstdint> #include <string>
namespace Net {
using namespace std;
class TcpServer { private: int32_t m_ListenFd; int32_t m_ClientFd; string m_ClientIp; uint16_t m_Port; public: TcpServer(); ~TcpServer();
bool Init(const uint16_t inPort); bool Accept(); bool Send(const string& buffer); bool Recv(string& buffer, const size_t maxLen); bool CloseClient(); bool Close();
const string& GetClientIp() const { return m_ClientIp; } };
}
#include "TcpServer.h"
#include <arpa/inet.h> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <netinet/in.h> #include <string> #include <sys/socket.h> #include <unistd.h>
namespace Net {
TcpServer::TcpServer() : m_ListenFd(-1), m_ClientFd(-1) {}
TcpServer::~TcpServer() { CloseClient(); Close(); }
bool TcpServer::Init(const uint16_t inPort) { if (m_ListenFd != -1) return false;
m_Port = inPort; m_ListenFd = socket(AF_INET, SOCK_STREAM, 0); if (m_ListenFd == -1) { perror("socket"); return false; }
struct sockaddr_in serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); serverAddr.sin_port = htons(m_Port); if (bind(m_ListenFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) { perror("bind"); close(m_ListenFd); return false; }
if (listen(m_ListenFd, 5) != 0) { perror("listen"); close(m_ListenFd); return false; }
return true; }
bool TcpServer::Accept() { struct sockaddr_in clientAddr; socklen_t addrLen = sizeof(clientAddr); if ((m_ClientFd = accept(m_ListenFd, (struct sockaddr*)&clientAddr, &addrLen)) == -1) { return false; } m_ClientIp = inet_ntoa(clientAddr.sin_addr); return true; }
bool TcpServer::Send(const string& buffer) { if (m_ClientFd == -1) return false; if ((send(m_ClientFd, buffer.data(), buffer.size(), 0)) <= 0) return false; return true; }
bool TcpServer::Recv(string& buffer, const size_t maxLen) { buffer.clear(); buffer.resize(maxLen); int n = recv(m_ClientFd, &buffer[0], buffer.size(), 0); if (n <= 0 ) { buffer.clear(); return false; } buffer.resize(n);
return true; }
bool TcpServer::CloseClient() { if (m_ClientFd == -1) return false;
close(m_ClientFd); m_ClientFd = -1;
return true; }
bool TcpServer::Close() { if (m_ListenFd == -1) return false;
close(m_ListenFd); m_ClientFd = -1;
return true; }
}
|