Skip to content

Commit 1ecd626

Browse files
committed
Refactor
1 parent 49597c5 commit 1ecd626

File tree

7 files changed

+149
-161
lines changed

7 files changed

+149
-161
lines changed

async-sockets/include/basesocket.hpp

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,12 @@
1313
#include <string>
1414
#include <functional>
1515
#include <cerrno>
16-
#include <atomic>
1716

1817
#define FDR_UNUSED(expr){ (void)(expr); }
1918
#define FDR_ON_ERROR std::function<void(int, std::string)> onError = [](int errorCode, std::string errorMessage){FDR_UNUSED(errorCode); FDR_UNUSED(errorMessage)}
2019

2120
class BaseSocket
2221
{
23-
// Definitions
2422
public:
2523
enum SocketType
2624
{
@@ -30,9 +28,20 @@ class BaseSocket
3028
sockaddr_in address;
3129
constexpr static uint16_t BUFFER_SIZE = 0x1000; // 4096 bytes
3230

31+
void Close() {
32+
shutdown(this->sock, SHUT_RDWR);
33+
close(this->sock);
34+
}
35+
36+
std::string remoteAddress() const { return ipToString(this->address); }
37+
int remotePort() const { return ntohs(this->address.sin_port); }
38+
int fileDescriptor() const { return this->sock; }
39+
3340
protected:
3441
int sock = 0;
35-
static std::string ipToString(sockaddr_in addr)
42+
43+
// Get std::string value of the IP from a `sockaddr_in` address struct
44+
static std::string ipToString(const sockaddr_in& addr)
3645
{
3746
char ip[INET_ADDRSTRLEN];
3847
inet_ntop(AF_INET, &(addr.sin_addr), ip, INET_ADDRSTRLEN);
@@ -42,9 +51,11 @@ class BaseSocket
4251

4352
BaseSocket(FDR_ON_ERROR, SocketType sockType = TCP, int socketId = -1)
4453
{
45-
if (socketId < 0)
54+
if (socketId == -1)
4655
{
47-
if ((this->sock = socket(AF_INET, sockType, 0)) < 0)
56+
this->sock = socket(AF_INET, sockType, 0);
57+
58+
if ( this->sock == -1 )
4859
{
4960
onError(errno, "Socket creating error.");
5061
}
@@ -54,14 +65,5 @@ class BaseSocket
5465
this->sock = socketId;
5566
}
5667
}
57-
58-
// Methods
59-
public:
60-
virtual void Close() {
61-
close(this->sock);
62-
}
63-
64-
std::string remoteAddress() {return ipToString(this->address);}
65-
int remotePort() {return ntohs(this->address.sin_port);}
66-
int fileDescriptor() const { return this->sock; }
68+
virtual ~BaseSocket(){}
6769
};

async-sockets/include/tcpserver.hpp

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -16,30 +16,37 @@ class TCPServer : public BaseSocket
1616
setsockopt(this->sock,SOL_SOCKET,SO_REUSEPORT,&opt,sizeof(int));
1717
}
1818

19-
// Binding the server.
19+
// Bind the custom address & port of the server.
2020
void Bind(const char* address, uint16_t port, FDR_ON_ERROR)
2121
{
22-
if (inet_pton(AF_INET, address, &this->address.sin_addr) <= 0)
23-
{
24-
onError(errno, "Invalid address. Address type not supported.");
25-
return;
22+
int status = inet_pton(AF_INET, address, &this->address.sin_addr);
23+
switch (status) {
24+
case -1:
25+
onError(errno, "Invalid address. Address type not supported.");
26+
return;
27+
case 0:
28+
onError(errno, "AF_INET is not supported. Please send message to developer.");
29+
return;
30+
default:
31+
break;
2632
}
2733

2834
this->address.sin_family = AF_INET;
2935
this->address.sin_port = htons(port);
3036

31-
if (bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address)) < 0)
37+
if (bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address)) == -1)
3238
{
3339
onError(errno, "Cannot bind the socket.");
3440
return;
3541
}
3642
}
37-
void Bind(int port, FDR_ON_ERROR) { this->Bind("0.0.0.0", port, onError); }
43+
// Bind the address(0.0.0.0) & port of the server.
44+
void Bind(uint16_t port, FDR_ON_ERROR) { this->Bind("0.0.0.0", port, onError); }
3845

39-
// Start listening the server.
46+
// Start listening incoming connections.
4047
void Listen(FDR_ON_ERROR)
4148
{
42-
if (listen(this->sock, 20) < 0)
49+
if (listen(this->sock, 20) == -1)
4350
{
4451
onError(errno, "Error: Server can't listen the socket.");
4552
return;
@@ -49,40 +56,31 @@ class TCPServer : public BaseSocket
4956
t.detach();
5057
}
5158

52-
// Overriding Close to add shutdown():
53-
void Close()
54-
{
55-
shutdown(this->sock, SHUT_RDWR);
56-
57-
BaseSocket::Close();
58-
}
59-
6059
private:
6160
static void Accept(TCPServer* server, FDR_ON_ERROR)
6261
{
6362
sockaddr_in newSocketInfo;
6463
socklen_t newSocketInfoLength = sizeof(newSocketInfo);
6564

66-
int newSock = -1;
65+
int newSocketFileDescriptor = -1;
6766
while (true)
6867
{
69-
if ((newSock = accept(server->sock, (sockaddr*)&newSocketInfo, &newSocketInfoLength)) < 0)
68+
newSocketFileDescriptor = accept(server->sock, (sockaddr*)&newSocketInfo, &newSocketInfoLength);
69+
if (newSocketFileDescriptor == -1)
7070
{
7171
if (errno == EBADF || errno == EINVAL) return;
7272

7373
onError(errno, "Error while accepting a new connection.");
74+
7475
return;
7576
}
7677

77-
if (newSock >= 0)
78-
{
79-
TCPSocket* newSocket = new TCPSocket(onError, newSock);
80-
newSocket->deleteAfterClosed = true;
81-
newSocket->setAddressStruct(newSocketInfo);
78+
TCPSocket* newSocket = new TCPSocket(onError, newSocketFileDescriptor);
79+
newSocket->deleteAfterClosed = true;
80+
newSocket->setAddressStruct(newSocketInfo);
8281

83-
server->onNewConnection(newSocket);
84-
newSocket->Listen();
85-
}
82+
server->onNewConnection(newSocket);
83+
newSocket->Listen();
8684
}
8785
}
8886
};

async-sockets/include/tcpsocket.hpp

Lines changed: 34 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,43 @@ class TCPSocket : public BaseSocket
1111
public:
1212
// Event Listeners:
1313
std::function<void(std::string)> onMessageReceived;
14-
std::function<void(const char*, int)> onRawMessageReceived;
14+
std::function<void(const char*, ssize_t)> onRawMessageReceived;
1515
std::function<void(int)> onSocketClosed;
1616

1717
explicit TCPSocket(FDR_ON_ERROR, int socketId = -1) : BaseSocket(onError, TCP, socketId){}
1818

19-
// Send TCP Packages
20-
int Send(const char* bytes, size_t byteslength)
19+
// Send raw bytes
20+
ssize_t Send(const char* bytes, size_t byteslength) { return send(this->sock, bytes, byteslength, 0); }
21+
// Send std::string
22+
ssize_t Send(const std::string& message) { return this->Send(message.c_str(), message.length()); }
23+
24+
// Connect to a TCP Server with `uint32_t ipv4` & `uint16_t port` values
25+
void Connect(uint32_t ipv4, uint16_t port, std::function<void()> onConnected = [](){}, FDR_ON_ERROR)
2126
{
22-
int sent = -1;
23-
if ((sent = send(this->sock, bytes, byteslength, 0)) < 0)
27+
this->address.sin_family = AF_INET;
28+
this->address.sin_port = htons(port);
29+
this->address.sin_addr.s_addr = ipv4;
30+
31+
this->setTimeout(5);
32+
33+
// Try to connect.
34+
int status = connect(this->sock, (const sockaddr*)&this->address, sizeof(sockaddr_in));
35+
if ( status == -1)
2436
{
25-
perror("send");
37+
onError(errno, "Connection failed to the host.");
38+
this->setTimeout(0);
39+
return;
2640
}
27-
return sent;
28-
}
29-
int Send(const std::string& message) { return this->Send(message.c_str(), message.length()); }
3041

42+
this->setTimeout(0);
43+
44+
// Connected to the server, fire the event.
45+
onConnected();
3146

47+
// Start listening from server:
48+
this->Listen();
49+
}
50+
// Connect to a TCP Server with `const char* host` & `uint16_t port` values
3251
void Connect(const char* host, uint16_t port, std::function<void()> onConnected = [](){}, FDR_ON_ERROR)
3352
{
3453
struct addrinfo hints, *res, *it;
@@ -37,8 +56,8 @@ class TCPSocket : public BaseSocket
3756
hints.ai_socktype = SOCK_STREAM;
3857

3958
// Get address info from DNS
40-
int status;
41-
if ((status = getaddrinfo(host, NULL, &hints, &res)) != 0) {
59+
int status = getaddrinfo(host, NULL, &hints, &res);
60+
if ( status != 0 ) {
4261
onError(errno, "Invalid address." + std::string(gai_strerror(status)));
4362
return;
4463
}
@@ -47,43 +66,21 @@ class TCPSocket : public BaseSocket
4766
{
4867
if (it->ai_family == AF_INET) { // IPv4
4968
memcpy((void*)(&this->address), (void*)it->ai_addr, sizeof(sockaddr_in));
50-
break; // for now, just get first ip (ipv4).
69+
break; // for now, just get the first ip (ipv4).
5170
}
5271
}
5372

5473
freeaddrinfo(res);
5574

5675
this->Connect((uint32_t)this->address.sin_addr.s_addr, port, onConnected, onError);
5776
}
58-
void Connect(uint32_t ipv4, uint16_t port, std::function<void()> onConnected = [](){}, FDR_ON_ERROR)
59-
{
60-
this->address.sin_family = AF_INET;
61-
this->address.sin_port = htons(port);
62-
this->address.sin_addr.s_addr = ipv4;
63-
64-
this->setTimeout(5);
65-
66-
// Try to connect.
67-
if (connect(this->sock, (const sockaddr*)&this->address, sizeof(sockaddr_in)) < 0)
68-
{
69-
onError(errno, "Connection failed to the host.");
70-
this->setTimeout(0);
71-
return;
72-
}
73-
74-
this->setTimeout(0);
75-
76-
// Connected to the server, fire the event.
77-
onConnected();
78-
79-
// Start listening from server:
80-
this->Listen();
81-
}
77+
// Connect to a TCP Server with `const std::string& ipv4` & `uint16_t port` values
8278
void Connect(const std::string& host, uint16_t port, std::function<void()> onConnected = [](){}, FDR_ON_ERROR)
8379
{
8480
this->Connect(host.c_str(), port, onConnected, onError);
8581
}
8682

83+
// Start another thread to listen the socket
8784
void Listen()
8885
{
8986
std::thread t(TCPSocket::Receive, this);
@@ -99,7 +96,7 @@ class TCPSocket : public BaseSocket
9996
static void Receive(TCPSocket* socket)
10097
{
10198
char tempBuffer[TCPSocket::BUFFER_SIZE];
102-
int messageLength;
99+
ssize_t messageLength;
103100

104101
while ((messageLength = recv(socket->sock, tempBuffer, TCPSocket::BUFFER_SIZE, 0)) > 0)
105102
{

async-sockets/include/udpserver.hpp

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,44 @@
66
class UDPServer : public UDPSocket
77
{
88
public:
9-
void Bind(const char* IPv4, std::uint16_t port, FDR_ON_ERROR)
9+
// Bind the custom address & port of the server.
10+
void Bind(const char* address, std::uint16_t port, FDR_ON_ERROR)
1011
{
11-
if (inet_pton(AF_INET, IPv4, &this->address.sin_addr) <= 0)
12-
{
13-
onError(errno, "Invalid address. Address type not supported.");
14-
return;
12+
int status = inet_pton(AF_INET, address, &this->address.sin_addr);
13+
switch (status) {
14+
case -1:
15+
onError(errno, "Invalid address. Address type not supported.");
16+
return;
17+
case 0:
18+
onError(errno, "AF_INET is not supported. Please send message to developer.");
19+
return;
20+
default:
21+
break;
1522
}
1623

1724
this->address.sin_family = AF_INET;
1825
this->address.sin_port = htons(port);
1926

20-
if (bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address)) < 0)
27+
status = bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address));
28+
if (status == -1)
2129
{
2230
onError(errno, "Cannot bind the socket.");
2331
return;
2432
}
2533
}
2634

27-
void Bind(int port, FDR_ON_ERROR)
35+
// Bind the address(0.0.0.0) & port of the server.
36+
void Bind(uint16_t port, FDR_ON_ERROR)
2837
{
2938
this->Bind("0.0.0.0", port, onError);
3039
}
3140

32-
void setBroadcast(FDR_ON_ERROR)
41+
// Enable or disable the SO_BROADCAST flag
42+
void setBroadcast(bool value, FDR_ON_ERROR)
3343
{
34-
int broadcast = 1;
35-
if (setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast))
44+
int broadcast = static_cast<int>(value);
45+
int status = setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast);
46+
if (status == -1)
3647
{
3748
onError(errno, "setsockopt(SO_BROADCAST) failed.");
3849
return;

0 commit comments

Comments
 (0)