Add TCP support #12

Merged
Persson-dev merged 12 commits from tcp into main 2025-03-03 10:04:42 +00:00
10 changed files with 489 additions and 4 deletions
Showing only changes of commit 4b2e4ca132 - Show all commits

View File

@@ -35,6 +35,7 @@ class DataBuffer {
typedef Data::difference_type difference_type;
DataBuffer();
DataBuffer(std::size_t a_InitialSize);
DataBuffer(const DataBuffer& other);
DataBuffer(const DataBuffer& other, difference_type offset);
DataBuffer(DataBuffer&& other);

View File

@@ -0,0 +1,25 @@
#pragma once
/**
* \file NonCopyable.h
* \brief File containing the sp::NonCopyable class
*/
namespace sp {
/**
* \class NonCopyable
* \brief Class used to make a class non copyable
* \note Inherit from this class privately to make a class non copyable
*/
class NonCopyable {
public:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
protected:
NonCopyable() {}
~NonCopyable() {}
};
} // namespace sp

View File

@@ -2,4 +2,8 @@
#if __has_include(<sp/extensions/Compress.h>)
#include <sp/extensions/Compress.h>
#endif
#if __has_include(<sp/extensions/Tcp.h>)
#include <sp/extensions/Tcp.h>
#endif

View File

@@ -0,0 +1,4 @@
#pragma once
#include <sp/extensions/tcp/TcpListener.h>
#include <sp/extensions/tcp/TcpSocket.h>

View File

@@ -0,0 +1,65 @@
#pragma once
#include <sp/extensions/tcp/TcpSocket.h>
namespace sp {
namespace io {
/**
* \class TcpListener
*/
class TcpListener : private NonCopyable {
public:
/**
* \brief Starts listening for guests to connect
* \param port The port to listen to
* \param maxConnexions The maximum amount of connexion that can happen at the same time. \n
* Every other guests will be kicked if this amount is reached.
* \return Whether this action was succesfull
*/
TcpListener(std::uint16_t a_Port, int a_MaxConnexions);
/**
* \brief Default destructor
*/
~TcpListener();
/**
* \brief Tries to accept an incoming request to connect
* \return the new socket if a new connexion was accepted or nullptr
*/
std::unique_ptr<TcpSocket> Accept();
/**
* \brief Closes the socket
*/
void Close();
/**
* \brief Allows to set the socket in non blocking/blocking mode
* \param a_Blocking If set to true, every call to Read will wait until the socket receives something
* \return true if the operation was successful
*/
bool SetBlocking(bool a_Blocking);
/**
* \brief Getter of the m_Port member
* \return The port which the socket listen to
*/
std::uint16_t GetListeningPort() const;
/**
* \brief Getter of the m_MaxConnections member
* \return The maximum amount of connexions that can happen at the same time.
*/
int GetMaximumConnections() const;
private:
SocketHandle m_Handle;
std::uint16_t m_Port;
int m_MaxConnections;
};
} // namespace io
} // namespace sp

View File

@@ -0,0 +1,85 @@
#pragma once
#include <sp/common/NonCopyable.h>
#include <sp/io/IOInterface.h>
namespace sp {
namespace io {
using SocketHandle = int;
struct TcpTag {};
class SocketError : public std::exception {
private:
std::string m_Error;
public:
SocketError(std::string&& a_Msg) : m_Error(std::move(a_Msg)) {}
virtual const char* what() const noexcept override {
return m_Error.c_str();
}
};
template <>
class IOInterface<TcpTag> : private NonCopyable {
public:
/**
* \enum Status
* \brief Describes the state of a socket
*/
enum class Status {
/** The socket is connected */
Connected,
/** The socket is not connected */
Disconnected,
/** Something bad happened */
Error,
};
IOInterface();
IOInterface(const std::string& a_Host, std::uint16_t a_Port);
IOInterface(IOInterface&& a_Other);
virtual ~IOInterface();
DataBuffer Read(std::size_t a_Amount);
void Write(const sp::DataBuffer& a_Data);
/**
* \brief Allows to set the socket in non blocking/blocking mode
* \param a_Block If set to true, every call to Read will wait until the socket receives something
* \return true if the operation was successful
*/
bool SetBlocking(bool a_Block);
/**
* \brief Getter of the m_Status member
* \return The TcpSocket::Status of this socket
*/
Status GetStatus() const;
/**
* \brief Disconnects the socket from the remote
* \note Does nothing if the socket is not connected. \n
* This function is also called by the destructor.
*/
void Disconnect();
private:
SocketHandle m_Handle;
Status m_Status;
void Connect(const std::string& a_Host, std::uint16_t a_Port);
friend class TcpListener;
};
/**
* \typedef TcpSocket
*/
using TcpSocket = IOInterface<TcpTag>;
} // namespace io
} // namespace sp

View File

@@ -8,6 +8,8 @@ namespace sp {
DataBuffer::DataBuffer() : m_ReadOffset(0) {}
DataBuffer::DataBuffer(std::size_t a_InitialSize) : m_Buffer(a_InitialSize), m_ReadOffset(0) {}
DataBuffer::DataBuffer(const DataBuffer& other) : m_Buffer(other.m_Buffer), m_ReadOffset(other.m_ReadOffset) {}
DataBuffer::DataBuffer(DataBuffer&& other) : m_Buffer(std::move(other.m_Buffer)), m_ReadOffset(std::move(other.m_ReadOffset)) {}

View File

@@ -0,0 +1,114 @@
#include <sp/extensions/tcp/TcpListener.h>
#ifdef _WIN32
// Windows
#include <winsock2.h>
#include <ws2tcpip.h>
#define ioctl ioctlsocket
#define WOULDBLOCK WSAEWOULDBLOCK
#define MSG_DONTWAIT 0
#else
// Linux/Unix
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define closesocket close
#define WOULDBLOCK EWOULDBLOCK
#define SD_BOTH SHUT_RDWR
#endif
#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif
namespace sp {
namespace io {
TcpListener::TcpListener(std::uint16_t a_Port, int a_MaxConnexions) {
if ((m_Handle = static_cast<SocketHandle>(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) < 0) {
throw SocketError("Failed to create server socket");
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(a_Port);
if (bind(m_Handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)) < 0)
throw SocketError("Failed to create server socket");
if (listen(m_Handle, a_MaxConnexions) < 0)
throw SocketError("Failed to create server socket");
socklen_t len = sizeof(address);
if (getsockname(m_Handle, reinterpret_cast<sockaddr*>(&address), &len) < 0)
throw SocketError("Failed to create server socket");
m_Port = ntohs(address.sin_port);
m_MaxConnections = a_MaxConnexions;
}
TcpListener::~TcpListener() {
Close();
}
std::unique_ptr<TcpSocket> TcpListener::Accept() {
sockaddr remoteAddress;
int addrlen = sizeof(remoteAddress);
auto newSocket = std::make_unique<TcpSocket>();
newSocket->m_Handle = static_cast<SocketHandle>(
accept(m_Handle, reinterpret_cast<sockaddr*>(&remoteAddress), reinterpret_cast<socklen_t*>(&addrlen)));
if (newSocket->m_Handle < 0)
return nullptr;
newSocket->m_Status = TcpSocket::Status::Connected;
return newSocket;
}
void TcpListener::Close() {
if (m_Handle > 0) {
closesocket(m_Handle);
shutdown(m_Handle, SD_BOTH);
}
}
bool TcpListener::SetBlocking(bool a_Blocking) {
unsigned long mode = !a_Blocking;
if (ioctl(m_Handle, FIONBIO, &mode) < 0) {
return false;
}
return true;
}
std::uint16_t TcpListener::GetListeningPort() const {
return m_Port;
}
int TcpListener::GetMaximumConnections() const {
return m_MaxConnections;
}
} // namespace io
} // namespace sp

View File

@@ -0,0 +1,157 @@
#include <sp/extensions/tcp/TcpSocket.h>
#ifdef _WIN32
// Windows
#include <winsock2.h>
#include <ws2tcpip.h>
#define ioctl ioctlsocket
#define WOULDBLOCK WSAEWOULDBLOCK
#define MSG_DONTWAIT 0
#else
// Linux/Unix
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define closesocket close
#define WOULDBLOCK EWOULDBLOCK
#endif
#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif
namespace sp {
namespace io {
TcpSocket::IOInterface() : m_Handle(static_cast<SocketHandle>(INVALID_SOCKET)), m_Status(Status::Disconnected) {}
TcpSocket::IOInterface(const std::string& a_Host, std::uint16_t a_Port) : IOInterface() {
Connect(a_Host, a_Port);
}
TcpSocket::IOInterface(IOInterface&& a_Other) {}
TcpSocket::~IOInterface() {}
void TcpSocket::Connect(const std::string& a_Host, std::uint16_t a_Port) {
struct addrinfo hints {};
struct addrinfo* result = nullptr;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
m_Status = Status::Error;
if (getaddrinfo(a_Host.c_str(), std::to_string(static_cast<int>(a_Port)).c_str(), &hints, &result) != 0) {
throw SocketError("Failed to get address info");
}
m_Handle = static_cast<SocketHandle>(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
if (m_Handle < 0) {
throw SocketError("Failed to create socket");
}
struct addrinfo* ptr = nullptr;
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
struct sockaddr* sockaddr = ptr->ai_addr;
if (connect(m_Handle, sockaddr, sizeof(sockaddr_in)) == 0) {
break;
}
}
freeaddrinfo(result);
if (!ptr) {
throw SocketError("Could not find a suitable interface for connecting");
}
m_Status = Status::Connected;
}
DataBuffer TcpSocket::Read(std::size_t a_Amount) {
DataBuffer buffer(a_Amount);
std::size_t totalRecieved = 0;
while (totalRecieved < a_Amount) {
int recvAmount = recv(m_Handle, reinterpret_cast<char*>(buffer.data() + totalRecieved), static_cast<int>(a_Amount - totalRecieved), 0);
if (recvAmount <= 0) {
#if defined(_WIN32) || defined(WIN32)
int err = WSAGetLastError();
#else
int err = errno;
#endif
if (err == WOULDBLOCK) {
m_Status = Status::Error;
throw SocketError("Error while reading");
}
Disconnect();
m_Status = Status::Error;
throw SocketError("Error while reading");
}
totalRecieved += recvAmount;
}
return buffer;
}
void TcpSocket::Write(const sp::DataBuffer& a_Data) {
if (GetStatus() != Status::Connected)
return;
std::size_t sent = 0;
while (sent < a_Data.GetSize()) {
int cur = send(m_Handle, reinterpret_cast<const char*>(a_Data.GetSize() + sent), static_cast<int>(a_Data.GetSize() - sent), 0);
if (cur <= 0) {
Disconnect();
m_Status = Status::Error;
return;
}
sent += static_cast<std::size_t>(cur);
}
}
bool TcpSocket::SetBlocking(bool a_Block) {
unsigned long mode = !a_Block;
if (ioctl(m_Handle, FIONBIO, &mode) < 0) {
return false;
}
return true;
}
TcpSocket::Status TcpSocket::GetStatus() const {
return m_Status;
}
void TcpSocket::Disconnect() {
if (m_Handle > 0)
closesocket(m_Handle);
m_Status = Status::Disconnected;
}
} // namespace io
} // namespace sp

View File

@@ -6,12 +6,21 @@ local modules = {
Compression = {
Option = "zlib",
Deps = {"zlib"},
Packages = {"zlib"},
Includes = {"include/(sp/extensions/Compress.h)"},
Sources = {"src/sp/extensions/Compress.cpp"}
},
TcpSocket = {
Option = "tcp",
Deps = {},
Includes = {"include/(sp/extensions/Tcp.h)"},
Sources = {"src/sp/extensions/Tcp*.cpp"}
}
}
-- Map modules to options
for name, module in table.orderpairs(modules) do
if module.Option then
@@ -19,6 +28,10 @@ for name, module in table.orderpairs(modules) do
end
end
-- Add modules requirements
for name, module in table.orderpairs(modules) do
if module.Deps then
@@ -26,6 +39,10 @@ for name, module in table.orderpairs(modules) do
end
end
-- Add modules targets
for name, module in table.orderpairs(modules) do
if module.Deps and has_config(module.Option) then
@@ -37,7 +54,7 @@ for name, module in table.orderpairs(modules) do
for _, source in table.orderpairs(module.Sources) do
add_files(source)
end
for _, package in table.orderpairs(module.Packages) do
for _, package in table.orderpairs(module.Deps) do
add_packages(package)
end
set_group("Library")
@@ -45,9 +62,15 @@ for name, module in table.orderpairs(modules) do
end
end
target("SimpleProtocol")
add_includedirs("include")
add_files("src/sp/**.cpp")
set_group("Library")
set_kind("$(kind)")
local includeFolders = {"common", "default", "io", "protocol"}
for _, folder in ipairs(includeFolders) do
@@ -63,8 +86,13 @@ target("SimpleProtocol")
-- we don't want extensions
remove_files("src/sp/extensions/**.cpp")
set_group("Library")
set_kind("$(kind)")
-- we need this for endian functions
if is_os("windows") then
add_links("ws2_32")
end
-- Tests
for _, file in ipairs(os.files("test/**.cpp")) do