diff --git a/.gitignore b/.gitignore index cdc6718..eb40e66 100644 --- a/.gitignore +++ b/.gitignore @@ -31,8 +31,10 @@ *.out *.app -examples/bin -benchmarks/easysocket/bin +examples/tcp-client +examples/tcp-server +examples/udp-client +examples/udp-server .vscode .idea cmake-build-debug diff --git a/async-sockets/include/basesocket.hpp b/async-sockets/include/basesocket.hpp index 144dcbf..a2ca33f 100644 --- a/async-sockets/include/basesocket.hpp +++ b/async-sockets/include/basesocket.hpp @@ -17,22 +17,34 @@ #define FDR_UNUSED(expr){ (void)(expr); } #define FDR_ON_ERROR std::function onError = [](int errorCode, std::string errorMessage){FDR_UNUSED(errorCode); FDR_UNUSED(errorMessage)} +#ifndef AS_DEFAULT_BUFFER_SIZE +#define AS_DEFAULT_BUFFER_SIZE 0x1000 /*4096 bytes*/ +#endif + class BaseSocket { -// Definitions public: enum SocketType { TCP = SOCK_STREAM, UDP = SOCK_DGRAM }; - const uint16_t BUFFER_SIZE = 0xFFFF; sockaddr_in address; - bool isClosed = false; + + void Close() { + shutdown(this->sock, SHUT_RDWR); + close(this->sock); + } + + std::string remoteAddress() const { return ipToString(this->address); } + int remotePort() const { return ntohs(this->address.sin_port); } + int fileDescriptor() const { return this->sock; } protected: int sock = 0; - static std::string ipToString(sockaddr_in addr) + + // Get std::string value of the IP from a `sockaddr_in` address struct + static std::string ipToString(const sockaddr_in& addr) { char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(addr.sin_addr), ip, INET_ADDRSTRLEN); @@ -42,9 +54,11 @@ class BaseSocket BaseSocket(FDR_ON_ERROR, SocketType sockType = TCP, int socketId = -1) { - if (socketId < 0) + if (socketId == -1) { - if ((this->sock = socket(AF_INET, sockType, 0)) < 0) + this->sock = socket(AF_INET, sockType, 0); + + if ( this->sock == -1 ) { onError(errno, "Socket creating error."); } @@ -54,17 +68,5 @@ class BaseSocket this->sock = socketId; } } - -// Methods -public: - virtual void Close() { - if(isClosed) return; - - isClosed = true; - close(this->sock); - } - - std::string remoteAddress() {return ipToString(this->address);} - int remotePort() {return ntohs(this->address.sin_port);} - int fileDescriptor() const { return this->sock; } + virtual ~BaseSocket(){} }; \ No newline at end of file diff --git a/async-sockets/include/tcpserver.hpp b/async-sockets/include/tcpserver.hpp index 6f93b12..e7beb59 100644 --- a/async-sockets/include/tcpserver.hpp +++ b/async-sockets/include/tcpserver.hpp @@ -3,11 +3,12 @@ #include "tcpsocket.hpp" #include +template class TCPServer : public BaseSocket { public: // Event Listeners: - std::function onNewConnection = [](TCPSocket* sock){FDR_UNUSED(sock)}; + std::function*)> onNewConnection = [](TCPSocket* sock){FDR_UNUSED(sock)}; explicit TCPServer(FDR_ON_ERROR): BaseSocket(onError, SocketType::TCP) { @@ -16,30 +17,37 @@ class TCPServer : public BaseSocket setsockopt(this->sock,SOL_SOCKET,SO_REUSEPORT,&opt,sizeof(int)); } - // Binding the server. - void Bind(const char *address, uint16_t port, FDR_ON_ERROR) + // Bind the custom address & port of the server. + void Bind(const char* address, uint16_t port, FDR_ON_ERROR) { - if (inet_pton(AF_INET, address, &this->address.sin_addr) <= 0) - { - onError(errno, "Invalid address. Address type not supported."); - return; + int status = inet_pton(AF_INET, address, &this->address.sin_addr); + switch (status) { + case -1: + onError(errno, "Invalid address. Address type not supported."); + return; + case 0: + onError(errno, "AF_INET is not supported. Please send message to developer."); + return; + default: + break; } this->address.sin_family = AF_INET; this->address.sin_port = htons(port); - if (bind(this->sock, (const sockaddr *)&this->address, sizeof(this->address)) < 0) + if (bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address)) == -1) { onError(errno, "Cannot bind the socket."); return; } } - void Bind(int port, FDR_ON_ERROR) { this->Bind("0.0.0.0", port, onError); } + // Bind the address(0.0.0.0) & port of the server. + void Bind(uint16_t port, FDR_ON_ERROR) { this->Bind("0.0.0.0", port, onError); } - // Start listening the server. + // Start listening incoming connections. void Listen(FDR_ON_ERROR) { - if (listen(this->sock, 20) < 0) + if (listen(this->sock, 20) == -1) { onError(errno, "Error: Server can't listen the socket."); return; @@ -49,40 +57,31 @@ class TCPServer : public BaseSocket t.detach(); } - // Overriding Close to add shutdown(): - void Close() - { - shutdown(this->sock, SHUT_RDWR); - - BaseSocket::Close(); - } - private: - static void Accept(TCPServer *server, FDR_ON_ERROR) + static void Accept(TCPServer* server, FDR_ON_ERROR) { sockaddr_in newSocketInfo; socklen_t newSocketInfoLength = sizeof(newSocketInfo); - int newSock; - while (!server->isClosed) + int newSocketFileDescriptor = -1; + while (true) { - while ((newSock = accept(server->sock, (sockaddr *)&newSocketInfo, &newSocketInfoLength)) < 0) + newSocketFileDescriptor = accept(server->sock, (sockaddr*)&newSocketInfo, &newSocketInfoLength); + if (newSocketFileDescriptor == -1) { if (errno == EBADF || errno == EINVAL) return; onError(errno, "Error while accepting a new connection."); + return; } - if (!server->isClosed && newSock >= 0) - { - TCPSocket *newSocket = new TCPSocket(onError, newSock); - newSocket->deleteAfterClosed = true; - newSocket->setAddressStruct(newSocketInfo); + TCPSocket* newSocket = new TCPSocket(onError, newSocketFileDescriptor); + newSocket->deleteAfterClosed = true; + newSocket->setAddressStruct(newSocketInfo); - server->onNewConnection(newSocket); - newSocket->Listen(); - } + server->onNewConnection(newSocket); + newSocket->Listen(); } } }; \ No newline at end of file diff --git a/async-sockets/include/tcpsocket.hpp b/async-sockets/include/tcpsocket.hpp index 586fc00..9ee8781 100644 --- a/async-sockets/include/tcpsocket.hpp +++ b/async-sockets/include/tcpsocket.hpp @@ -6,32 +6,50 @@ #include #include +template class TCPSocket : public BaseSocket { public: // Event Listeners: std::function onMessageReceived; - std::function onRawMessageReceived; + std::function onRawMessageReceived; std::function onSocketClosed; explicit TCPSocket(FDR_ON_ERROR, int socketId = -1) : BaseSocket(onError, TCP, socketId){} - // Send TCP Packages - int Send(const char *bytes, size_t byteslength) + // Send raw bytes + ssize_t Send(const char* bytes, size_t byteslength) { return send(this->sock, bytes, byteslength, 0); } + // Send std::string + ssize_t Send(const std::string& message) { return this->Send(message.c_str(), message.length()); } + + // Connect to a TCP Server with `uint32_t ipv4` & `uint16_t port` values + void Connect(uint32_t ipv4, uint16_t port, std::function onConnected = [](){}, FDR_ON_ERROR) { - if (this->isClosed) - return -1; + this->address.sin_family = AF_INET; + this->address.sin_port = htons(port); + this->address.sin_addr.s_addr = ipv4; - int sent = 0; - if ((sent = send(this->sock, bytes, byteslength, 0)) < 0) + this->setTimeout(5); + + // Try to connect. + int status = connect(this->sock, (const sockaddr*)&this->address, sizeof(sockaddr_in)); + if ( status == -1) { - perror("send"); + onError(errno, "Connection failed to the host."); + this->setTimeout(0); + return; } - return sent; - } - int Send(std::string message) { return this->Send(message.c_str(), message.length()); } - void Connect(std::string host, uint16_t port, std::function onConnected = [](){}, FDR_ON_ERROR) + this->setTimeout(0); + + // Connected to the server, fire the event. + onConnected(); + + // Start listening from server: + this->Listen(); + } + // Connect to a TCP Server with `const char* host` & `uint16_t port` values + void Connect(const char* host, uint16_t port, std::function onConnected = [](){}, FDR_ON_ERROR) { struct addrinfo hints, *res, *it; memset(&hints, 0, sizeof(hints)); @@ -39,8 +57,8 @@ class TCPSocket : public BaseSocket hints.ai_socktype = SOCK_STREAM; // Get address info from DNS - int status; - if ((status = getaddrinfo(host.c_str(), NULL, &hints, &res)) != 0) { + int status = getaddrinfo(host, NULL, &hints, &res); + if ( status != 0 ) { onError(errno, "Invalid address." + std::string(gai_strerror(status))); return; } @@ -49,7 +67,7 @@ class TCPSocket : public BaseSocket { if (it->ai_family == AF_INET) { // IPv4 memcpy((void*)(&this->address), (void*)it->ai_addr, sizeof(sockaddr_in)); - break; // for now, just get first ip (ipv4). + break; // for now, just get the first ip (ipv4). } } @@ -57,31 +75,13 @@ class TCPSocket : public BaseSocket this->Connect((uint32_t)this->address.sin_addr.s_addr, port, onConnected, onError); } - void Connect(uint32_t ipv4, uint16_t port, std::function onConnected = [](){}, FDR_ON_ERROR) + // Connect to a TCP Server with `const std::string& ipv4` & `uint16_t port` values + void Connect(const std::string& host, uint16_t port, std::function onConnected = [](){}, FDR_ON_ERROR) { - this->address.sin_family = AF_INET; - this->address.sin_port = htons(port); - this->address.sin_addr.s_addr = ipv4; - - this->setTimeout(5); - - // Try to connect. - if (connect(this->sock, (const sockaddr *)&this->address, sizeof(sockaddr_in)) < 0) - { - onError(errno, "Connection failed to the host."); - this->setTimeout(0); - return; - } - - this->setTimeout(0); - - // Connected to the server, fire the event. - onConnected(); - - // Start listening from server: - this->Listen(); + this->Connect(host.c_str(), port, onConnected, onError); } + // Start another thread to listen the socket void Listen() { std::thread t(TCPSocket::Receive, this); @@ -94,12 +94,12 @@ class TCPSocket : public BaseSocket bool deleteAfterClosed = false; private: - static void Receive(TCPSocket *socket) + static void Receive(TCPSocket* socket) { - char tempBuffer[socket->BUFFER_SIZE]; - int messageLength; + char tempBuffer[BUFFER_SIZE+1]; + ssize_t messageLength; - while ((messageLength = recv(socket->sock, tempBuffer, socket->BUFFER_SIZE, 0)) > 0) + while ((messageLength = recv(socket->sock, tempBuffer, BUFFER_SIZE, 0)) > 0) { tempBuffer[messageLength] = '\0'; if(socket->onMessageReceived) @@ -123,7 +123,7 @@ class TCPSocket : public BaseSocket tv.tv_sec = seconds; tv.tv_usec = 0; - setsockopt(this->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)); - setsockopt(this->sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)); + setsockopt(this->sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)); + setsockopt(this->sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv)); } }; diff --git a/async-sockets/include/udpserver.hpp b/async-sockets/include/udpserver.hpp index addccfc..65ba250 100644 --- a/async-sockets/include/udpserver.hpp +++ b/async-sockets/include/udpserver.hpp @@ -3,36 +3,48 @@ #include "udpsocket.hpp" #include -class UDPServer : public UDPSocket +template +class UDPServer : public UDPSocket { public: - void Bind(std::string IPv4, std::uint16_t port, FDR_ON_ERROR) + // Bind the custom address & port of the server. + void Bind(const char* address, std::uint16_t port, FDR_ON_ERROR) { - if (inet_pton(AF_INET, IPv4.c_str(), &this->address.sin_addr) <= 0) - { - onError(errno, "Invalid address. Address type not supported."); - return; + int status = inet_pton(AF_INET, address, &this->address.sin_addr); + switch (status) { + case -1: + onError(errno, "Invalid address. Address type not supported."); + return; + case 0: + onError(errno, "AF_INET is not supported. Please send message to developer."); + return; + default: + break; } this->address.sin_family = AF_INET; this->address.sin_port = htons(port); - if (bind(this->sock, (const sockaddr *)&this->address, sizeof(this->address)) < 0) + status = bind(this->sock, (const sockaddr*)&this->address, sizeof(this->address)); + if (status == -1) { onError(errno, "Cannot bind the socket."); return; } } - void Bind(int port, FDR_ON_ERROR) + // Bind the address(0.0.0.0) & port of the server. + void Bind(uint16_t port, FDR_ON_ERROR) { this->Bind("0.0.0.0", port, onError); } - void setBroadcast(FDR_ON_ERROR) + // Enable or disable the SO_BROADCAST flag + void setBroadcast(bool value, FDR_ON_ERROR) { - int broadcast = 1; - if (setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast)) + int broadcast = static_cast(value); + int status = setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast); + if (status == -1) { onError(errno, "setsockopt(SO_BROADCAST) failed."); return; diff --git a/async-sockets/include/udpsocket.hpp b/async-sockets/include/udpsocket.hpp index 11b7783..f9b8b9a 100644 --- a/async-sockets/include/udpsocket.hpp +++ b/async-sockets/include/udpsocket.hpp @@ -4,17 +4,17 @@ #include #include +template class UDPSocket : public BaseSocket { public: std::function onMessageReceived; - std::function onRawMessageReceived; + std::function onRawMessageReceived; explicit UDPSocket(bool useConnect = false, FDR_ON_ERROR, int socketId = -1): BaseSocket(onError, SocketType::UDP, socketId) { if (useConnect) { - std::thread t(Receive, this); // usage with Connect() t.detach(); } @@ -25,8 +25,8 @@ class UDPSocket : public BaseSocket } } - // SendTo with no connection - void SendTo(const char *bytes, size_t byteslength, std::string host, uint16_t port, FDR_ON_ERROR) + // Send raw bytes to a spesific `host` & `port` with no connection + ssize_t SendTo(const char* bytes, size_t byteslength, const char* host, uint16_t port, FDR_ON_ERROR) { sockaddr_in hostAddr; @@ -36,17 +36,17 @@ class UDPSocket : public BaseSocket hints.ai_socktype = SOCK_DGRAM; int status; - if ((status = getaddrinfo(host.c_str(), NULL, &hints, &res)) != 0) + if ((status = getaddrinfo(host, NULL, &hints, &res)) != 0) { onError(errno, "Invalid address." + std::string(gai_strerror(status))); - return; + return -1; } for (it = res; it != NULL; it = it->ai_next) { if (it->ai_family == AF_INET) { // IPv4 - memcpy((void *)(&hostAddr), (void *)it->ai_addr, sizeof(sockaddr_in)); + memcpy((void* )(&hostAddr), (void* )it->ai_addr, sizeof(sockaddr_in)); break; // for now, just get first ip (ipv4). } } @@ -55,37 +55,38 @@ class UDPSocket : public BaseSocket hostAddr.sin_port = htons(port); hostAddr.sin_family = AF_INET; - - if (sendto(this->sock, bytes, byteslength, 0, (sockaddr *)&hostAddr, sizeof(hostAddr)) < 0) + + ssize_t sent_length = sendto(this->sock, bytes, byteslength, 0, (sockaddr*)&hostAddr, sizeof(hostAddr)); + if (sent_length == -1) { onError(errno, "Cannot send message to the address."); - return; + return -1; } + + return sent_length; } - void SendTo(std::string message, std::string host, uint16_t port, FDR_ON_ERROR) + // Send raw bytes to a spesific `host` & `port` with no connection + ssize_t SendTo(const char* bytes, size_t byteslength, const std::string& host, uint16_t port, FDR_ON_ERROR) { - this->SendTo(message.c_str(), message.length(), host, port, onError); + return this->SendTo(bytes, byteslength, host.c_str(), port, onError); } - - // Send with Connect() - int Send(const char *bytes, size_t byteslength) + // Send std::string to a spesific `host` & `port` with no connection + ssize_t SendTo(const std::string& message, const char* host, uint16_t port, FDR_ON_ERROR) { - if (this->isClosed) - return -1; - - int sent = 0; - if ((sent = send(this->sock, bytes, byteslength, 0)) < 0) - { - perror("send"); - } - return sent; + return this->SendTo(message.c_str(), message.length(), host, port, onError); } - int Send(std::string message) + // Send std::string to a spesific `host` & `port` with no connection + ssize_t SendTo(const std::string& message, const std::string& host, uint16_t port, FDR_ON_ERROR) { - return this->Send(message.c_str(), message.length()); + return this->SendTo(message.c_str(), message.length(), host.c_str(), port, onError); } - // To use "Send()", need to call Connect() first + // Send raw bytes to the `Connect()`ed server. + ssize_t Send(const char* bytes, size_t byteslength) { return send(this->sock, bytes, byteslength, 0); } + // Send std::string to the `Connect()`ed server. + ssize_t Send(const std::string& message) { return this->Send(message.c_str(), message.length()); } + + // Connect to a server with raw `uint32_t ipv4` and `uint16_t port` values. void Connect(uint32_t ipv4, uint16_t port, FDR_ON_ERROR) { this->address.sin_family = AF_INET; @@ -93,21 +94,23 @@ class UDPSocket : public BaseSocket this->address.sin_addr.s_addr = ipv4; // Try to connect. - if (connect(this->sock, (const sockaddr *)&this->address, sizeof(sockaddr_in)) < 0) + int status = connect(this->sock, (const sockaddr* )&this->address, sizeof(sockaddr_in)); + if (status == -1) { onError(errno, "Connection failed to the host."); return; } } - void Connect(std::string host, uint16_t port, FDR_ON_ERROR) + // Connect to a server with `host` address and `port` values. + void Connect(const char* host, uint16_t port, FDR_ON_ERROR) { struct addrinfo hints, *res, *it; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; - int status; - if ((status = getaddrinfo(host.c_str(), NULL, &hints, &res)) != 0) + int status = getaddrinfo(host, NULL, &hints, &res); + if (status != 0) { onError(errno, "Invalid address." + std::string(gai_strerror(status))); return; @@ -117,7 +120,7 @@ class UDPSocket : public BaseSocket { if (it->ai_family == AF_INET) { // IPv4 - memcpy((void *)(&this->address), (void *)it->ai_addr, sizeof(sockaddr_in)); + memcpy((void* )(&this->address), (void*)it->ai_addr, sizeof(sockaddr_in)); break; // for now, just get first ip (ipv4). } } @@ -126,59 +129,42 @@ class UDPSocket : public BaseSocket this->Connect((uint32_t)this->address.sin_addr.s_addr, port, onError); } + // Connect to a server with `host` address and `port` values. + void Connect(const std::string& host, uint16_t port, FDR_ON_ERROR) { this->Connect(host.c_str(), port, onError); } private: - static void Receive(UDPSocket *udpSocket) + static void Receive(UDPSocket* udpSocket) { - char tempBuffer[udpSocket->BUFFER_SIZE]; + char tempBuffer[BUFFER_SIZE+1]; + ssize_t messageLength; - while (true) + while ((messageLength = recv(udpSocket->sock, tempBuffer, BUFFER_SIZE, 0)) != -1) { - int messageLength; - messageLength = recv(udpSocket->sock, tempBuffer, udpSocket->BUFFER_SIZE, 0); + tempBuffer[messageLength] = '\0'; + if (udpSocket->onMessageReceived) + udpSocket->onMessageReceived(std::string(tempBuffer, messageLength), ipToString(udpSocket->address), ntohs(udpSocket->address.sin_port)); - if (messageLength < 0) - { - perror("recvfrom"); - return; - } - else - { - tempBuffer[messageLength] = '\0'; - if (udpSocket->onMessageReceived) - udpSocket->onMessageReceived(std::string(tempBuffer, messageLength), ipToString(udpSocket->address), ntohs(udpSocket->address.sin_port)); - - if (udpSocket->onRawMessageReceived) - udpSocket->onRawMessageReceived(tempBuffer, messageLength, ipToString(udpSocket->address), ntohs(udpSocket->address.sin_port)); - } + if (udpSocket->onRawMessageReceived) + udpSocket->onRawMessageReceived(tempBuffer, messageLength, ipToString(udpSocket->address), ntohs(udpSocket->address.sin_port)); } } - static void ReceiveFrom(UDPSocket *udpSocket) + + static void ReceiveFrom(UDPSocket* udpSocket) { sockaddr_in hostAddr; socklen_t hostAddrSize = sizeof(hostAddr); - char tempBuffer[udpSocket->BUFFER_SIZE]; + char tempBuffer[BUFFER_SIZE+1]; + ssize_t messageLength; - while (true) + while ((messageLength = recvfrom(udpSocket->sock, tempBuffer, BUFFER_SIZE, 0, (sockaddr* )&hostAddr, &hostAddrSize)) != -1) { - int messageLength; - messageLength = recvfrom(udpSocket->sock, tempBuffer, udpSocket->BUFFER_SIZE, 0, (sockaddr *)&hostAddr, &hostAddrSize); + tempBuffer[messageLength] = '\0'; + if (udpSocket->onMessageReceived) + udpSocket->onMessageReceived(std::string(tempBuffer, messageLength), ipToString(hostAddr), ntohs(hostAddr.sin_port)); - if (messageLength < 0) - { - perror("recvfrom"); - return; - } - else - { - tempBuffer[messageLength] = '\0'; - if (udpSocket->onMessageReceived) - udpSocket->onMessageReceived(std::string(tempBuffer, messageLength), ipToString(hostAddr), ntohs(hostAddr.sin_port)); - - if (udpSocket->onRawMessageReceived) - udpSocket->onRawMessageReceived(tempBuffer, messageLength, ipToString(hostAddr), ntohs(hostAddr.sin_port)); - } + if (udpSocket->onRawMessageReceived) + udpSocket->onRawMessageReceived(tempBuffer, messageLength, ipToString(hostAddr), ntohs(hostAddr.sin_port)); } } }; \ No newline at end of file diff --git a/examples/Makefile b/examples/Makefile index fe78578..2cd389d 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -1,25 +1,27 @@ CC := g++ -CFLAGS := --std=c++11 +CFLAGS := --std=c++11 -Wall -Wextra -Werror=conversion LIBS := -lpthread -INC := -I../async-sockets/include +INC := ../async-sockets/include RM := rm +.PHONY: all clean + all: tcp-client tcp-server udp-client udp-server -tcp-client: - $(CC) $(CFLAGS) tcp-client.cpp $(INC) $(LIBS) -o tcp-client +tcp-client: tcp-client.cpp $(INC)/tcpsocket.hpp + $(CC) $(CFLAGS) $< -I$(INC) $(LIBS) -o $@ -tcp-server: - $(CC) $(CFLAGS) tcp-server.cpp $(INC) $(LIBS) -o tcp-server +tcp-server: tcp-server.cpp $(INC)/tcpserver.hpp + $(CC) $(CFLAGS) $< -I$(INC) $(LIBS) -o $@ -udp-client: - $(CC) $(CFLAGS) udp-client.cpp $(INC) $(LIBS) -o udp-client +udp-client: udp-client.cpp $(INC)/udpsocket.hpp + $(CC) $(CFLAGS) $< -I$(INC) $(LIBS) -o $@ -udp-server: - $(CC) $(CFLAGS) udp-server.cpp $(INC) $(LIBS) -o udp-server +udp-server: udp-server.cpp $(INC)/udpserver.hpp + $(CC) $(CFLAGS) $< -I$(INC) $(LIBS) -o $@ clean: $(RM) tcp-client $(RM) tcp-server $(RM) udp-client - $(RM) udp-server \ No newline at end of file + $(RM) udp-server diff --git a/examples/tcp-client.cpp b/examples/tcp-client.cpp index 27432c8..3e82b5e 100644 --- a/examples/tcp-client.cpp +++ b/examples/tcp-client.cpp @@ -1,4 +1,4 @@ -#include "../async-sockets/include/tcpsocket.hpp" +#include "tcpsocket.hpp" #include using namespace std; @@ -6,27 +6,26 @@ using namespace std; int main() { // Initialize socket. - TCPSocket tcpSocket([](int errorCode, std::string errorMessage){ + TCPSocket<> tcpSocket([](int errorCode, std::string errorMessage){ cout << "Socket creation error:" << errorCode << " : " << errorMessage << endl; }); // Start receiving from the host. - tcpSocket.onMessageReceived = [](string message) { - cout << "Message from the Server: " << message << endl; - }; - // If you want to use raw bytes instead of std::string: - /* tcpSocket.onRawMessageReceived = [](const char* message, int length) { cout << "Message from the Server: " << message << "(" << length << ")" << endl; }; - */ + + // If you want to use std::string instead of const char*: + //tcpSocket.onMessageReceived = [](string message) { + // cout << "Message from the Server: " << message << endl; + //}; // On socket closed: tcpSocket.onSocketClosed = [](int errorCode){ cout << "Connection closed: " << errorCode << endl; }; - // Connect to the host. + // Connect to the host (with a custom buffer size). tcpSocket.Connect("localhost", 8888, [&] { cout << "Connected to the server successfully." << endl; @@ -38,8 +37,7 @@ int main() cout << errorCode << " : " << errorMessage << endl; }); - // You should do an input loop so the program will not end immediately: - // Because socket listenings are non-blocking. + // You should do an input loop, so the program won't terminate immediately string input; getline(cin, input); while (input != "exit") diff --git a/examples/tcp-server.cpp b/examples/tcp-server.cpp index c5c3437..7c642b8 100644 --- a/examples/tcp-server.cpp +++ b/examples/tcp-server.cpp @@ -1,4 +1,4 @@ -#include "../async-sockets/include/tcpserver.hpp" +#include "tcpserver.hpp" #include using namespace std; @@ -6,10 +6,10 @@ using namespace std; int main() { // Initialize server socket.. - TCPServer tcpServer; + TCPServer<> tcpServer; // When a new client connected: - tcpServer.onNewConnection = [&](TCPSocket *newClient) { + tcpServer.onNewConnection = [&](TCPSocket<> *newClient) { cout << "New client: ["; cout << newClient->remoteAddress() << ":" << newClient->remotePort() << "]" << endl; @@ -44,7 +44,7 @@ int main() cout << errorCode << " : " << errorMessage << endl; }); - // You should do an input loop so the program will not terminated immediately: + // You should do an input loop, so the program won't terminate immediately string input; getline(cin, input); while (input != "exit") diff --git a/examples/udp-client.cpp b/examples/udp-client.cpp index bcaf2ba..d9e63aa 100644 --- a/examples/udp-client.cpp +++ b/examples/udp-client.cpp @@ -1,4 +1,4 @@ -#include "../async-sockets/include/udpsocket.hpp" +#include "udpsocket.hpp" #include using namespace std; @@ -6,11 +6,11 @@ using namespace std; int main() { // Our constants: - const string IP = "localhost"; - const uint16_t PORT = 8888; + constexpr const char* IP = "localhost"; + constexpr uint16_t PORT = 8888; // Initialize socket. - UDPSocket udpSocket(true); // "true" to use Connection on UDP. Default is "false". + UDPSocket<100> udpSocket(true); // "true" to use Connection on UDP. Default is "false". udpSocket.Connect(IP, PORT); // Send String: @@ -28,7 +28,7 @@ int main() }; */ - // You should do an input loop so the program will not terminated immediately: + // You should do an input loop, so the program won't terminate immediately string input; getline(cin, input); while (input != "exit") diff --git a/examples/udp-server.cpp b/examples/udp-server.cpp index 575c043..990bb2d 100644 --- a/examples/udp-server.cpp +++ b/examples/udp-server.cpp @@ -1,4 +1,4 @@ -#include "../async-sockets/include/udpserver.hpp" +#include "udpserver.hpp" #include using namespace std; @@ -6,22 +6,21 @@ using namespace std; int main() { // Initialize server socket.. - UDPServer udpServer; + UDPServer<> udpServer; // onMessageReceived will run when a message received with information of ip & port of sender: /*udpServer.onMessageReceived = [&](string message, string ipv4, uint16_t port) { //cout << ipv4 << ":" << port << " => " << message << endl; - // Just send without control: + // Echo to client: udpServer.SendTo("A!", ipv4, port); };*/ // If you want to use raw byte arrays: - udpServer.onRawMessageReceived = [&](const char* message, int length, string ipv4, uint16_t port) { - //cout << ipv4 << ":" << port << " => " << message << "(" << length << ")" << endl; + cout << ipv4 << ":" << port << " => " << message << "(" << length << ")" << endl; - // Just send without control: + // Echo to client: udpServer.SendTo(message, length, ipv4, port); }; @@ -32,7 +31,7 @@ int main() cout << errorCode << " : " << errorMessage << endl; }); - // You should do an input loop so the program will not terminated immediately: + // You should do an input loop, so the program won't terminate immediately string input; getline(cin, input); while (input != "exit")