120 lines
2.2 KiB
C++
120 lines
2.2 KiB
C++
#ifndef TCP_SERVER_H
|
|
#define TCP_SERVER_H
|
|
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <iostream>
|
|
#include <unistd.h>
|
|
#include <signal.h> // für signal() function, weil send gibt SIGPIPE zurück, (wenn letzter prozess beendet oder so... nur für schellscripts nötig),
|
|
//und da programm abstürzt. nicht wichtig für tcp
|
|
//#include <string.h>
|
|
#include <cstring> // std::strerror
|
|
|
|
|
|
#ifdef _WIN32
|
|
#include <winsock2.h>
|
|
//#include <windows.h>
|
|
//#include <ws2tcpip.h>
|
|
//#include <typeinfo>
|
|
|
|
#else
|
|
#ifdef __linux
|
|
#include <sys/socket.h>
|
|
#include <arpa/inet.h>
|
|
#include <netdb.h> // for hostent ( getIpByName-Func )
|
|
#endif
|
|
#endif
|
|
|
|
|
|
class CLIENT
|
|
{
|
|
public:
|
|
CLIENT();
|
|
~CLIENT();
|
|
|
|
void setAddress(const int &socket, const sockaddr_in &clientAddress);
|
|
int closeSocket();
|
|
|
|
ssize_t send_(const char * buffer, size_t __n, int flags = 0);
|
|
ssize_t recv_(char * buffer, size_t __n, int flags = 0);
|
|
|
|
std::string getLastError() const;
|
|
sockaddr_in getAddress() const;
|
|
std::string getIpAddress() const;
|
|
unsigned short getPort() const;
|
|
bool isConnected() const;
|
|
int getSocket() const;
|
|
|
|
bool autoCleanUpInTheEnd = true;
|
|
|
|
private:
|
|
void setErrorMessage(const std::string &txt, bool withPerrorText = false, bool closesocket = false);
|
|
|
|
sockaddr_in clientAddress;
|
|
size_t sizeof_sockaddr_in;
|
|
int clientSocket;
|
|
std::string errorMessage;
|
|
|
|
};
|
|
|
|
|
|
|
|
class TCP_SERVER
|
|
{
|
|
public:
|
|
TCP_SERVER();
|
|
~TCP_SERVER();
|
|
|
|
int startListening(const unsigned short &port, const int &maxWaitingQueque = 3, const unsigned int saddr = 0000 /*INADDR_ANY*/);
|
|
int stopListening();
|
|
bool isListening() const;
|
|
|
|
int acceptClient(CLIENT &client);
|
|
|
|
|
|
std::string getLastError() const;
|
|
int getListeningSocket() const;
|
|
unsigned short getListeningPort() const;
|
|
|
|
static std::string getIpByName(const std::string &name);
|
|
static std::string getHostName();
|
|
|
|
bool autoCleanUpInTheEnd = true;
|
|
|
|
private:
|
|
void setErrorMessage(const std::string &txt, bool withPerrorText = false, bool closesocket = false);
|
|
|
|
std::string errorMessage;
|
|
int listeningSocket;
|
|
unsigned short listeningPort;
|
|
size_t sizeof_sockaddr_in;
|
|
sockaddr_in serverAddresse;
|
|
};
|
|
|
|
#endif // TCP_SERVER_H
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|