#ifndef SOCK_SOCKET_H
#define SOCK_SOCKET_H
// #include <standard library headers>
#include <string>
// #include <other library headers>
#ifdef _WIN32
#include <Winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>
#endif
// #include "customer headers"
namespace sock
{
const int MAXSEND = 1000;
const int MAXRECV = 1000;
typedef int socklen_t;
#ifndef _WIN32
#define INVALID_SOCKET -1;
#define SOCKET_ERROR -1;
typedef int SOCKET;
#endif
#ifdef _WIN32
/**
* description
* @author meteor
*/
class WSAInitial
{
// ctor && dtor
public:
WSAInitial()
{
WSADATA wsaData;
if (WSAStartup(0x101, &wsaData))
{
exit(-1);
}
}
virtual ~WSAInitial() { WSACleanup(); }
}; // end of class WSAInitial
#endif
/**
* description
* @author meteor
*/
class SocketException : public std::exception
{
public:
SocketException(const std::string& s = "") : msg(s) {}
virtual ~SocketException() throw() {}
public:
virtual const char* what() const throw() { return msg.c_str(); }
virtual const std::string What() const throw() { return msg; }
private:
std::string msg;
}; // end of class SocketException
/**
* description
* @author meteor
*/
class Socket
{
public:
Socket();
virtual ~Socket();
public:
// Server initialization
bool Create();
bool Bind (const int port);
bool Listen() const;
bool Accept(Socket& newSocket, int sec = -1, int usec = -1) const;
// Client initialization
bool Connect(const std::string host, const int port);
// Data Transimission
bool Send(const std::string s, int sec = -1, int usec = -1) const;
bool Send(const char* buf, int len, int sec = -1, int usec = -1) const;
int Recv(std::string& s, int sec = -1, int usec = -1) const;
int Recv(char* buf, int len, int sec = -1, int usec = -1) const;
void SetNonBlocking(const bool b);
bool IsValid() const;
const sockaddr_in& GetSocketAddr() const { return mAddr; }
std::string GetIp() const { return inet_ntoa(mAddr.sin_addr); }
u_short GetPort() const { return ntohs(mAddr.sin_port); }
protected:
int Select(bool read, long sec, long usec) const;
private:
static void GetLastError();
private:
Socket(const Socket& sock);
Socket& operator = (const Socket& sock);
private:
SOCKET mSock;
sockaddr_in mAddr;
#ifdef _WIN32
static WSAInitial sWinsockInit;
#endif
}; // end of class Socket
}
#endif // SOCK_SOCKET_H
Socket封裝3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.