00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #ifndef IXE_io_Socket_H
00025 #define IXE_io_Socket_H
00026
00027
00028 #include "platform.h"
00029
00030
00031 #ifdef _WIN32
00032 # include <winsock2.h>
00033 # include <mswsock.h>
00034 # define MSG_DONTWAIT 0
00035 # define socklen_t int
00036 # define in_port_t u_short
00037 #else
00038 # include <arpa/inet.h>
00039 # include <sys/socket.h>
00040 # include <sys/time.h>
00041 # include <errno.h>
00042 # include <unistd.h>
00043 # define INVALID_SOCKET -1
00044 # define SOCKET_ERROR -1
00045 # define SOCKET int
00046 # define closesocket ::close
00047 #endif
00048
00049 #ifdef MSG_NOSIGNAL
00050 #define HAVE_MSG_NOSIGNAL
00051 #else
00052 #define MSG_NOSIGNAL 0
00053 #endif
00054
00055
00056 #include "include/error.h"
00057
00058 namespace IXE {
00059 namespace io {
00060
00061
00062 typedef unsigned long InetAddress;
00063
00067 class AbstractSocket
00068 {
00069 public:
00070
00071 ~AbstractSocket();
00072
00076 bool isOpen() const;
00077
00081 void close();
00082
00088 size_t read(char* buffer, size_t len);
00089
00095 size_t readAll(char* buffer, size_t len);
00096
00097 size_t write(char const* buffer, size_t len);
00098
00099 size_t write(char const* buffer) {
00100 return write(buffer, ::strlen(buffer));
00101 }
00102
00103 size_t write(std::string s) {
00104 return write(s.c_str(), s.length());
00105 }
00106
00107 SOCKET socket() { return sock; }
00108
00109 protected:
00110
00111 AbstractSocket(SOCKET sock = INVALID_SOCKET, InetAddress inetAddress = 0,
00112 in_port_t port = 0);
00113
00114 void copy(const AbstractSocket& r)
00115 {
00116 AbstractSocket& rhs = const_cast<AbstractSocket&>(r);
00117 sock = rhs.sock;
00118 inetAddress = rhs.inetAddress;
00119 port = rhs.port;
00120 rhs.sock = INVALID_SOCKET;
00121 }
00122
00123 SOCKET sock;
00124 InetAddress inetAddress;
00125 in_port_t port;
00126 };
00127
00132 class Socket : public AbstractSocket
00133 {
00134 public:
00138 Socket() { }
00139
00146 Socket(char const* host, int port);
00147
00151 Socket(Socket const& other) { copy(other); }
00152
00157 bool connect(char const* host, int port);
00158
00163 bool open();
00164
00168 InetAddress Address() { return inetAddress; }
00169
00173 in_port_t Port() { return port; }
00174
00175 Socket& operator =(const Socket& rhs)
00176 {
00177 if (&rhs != this) {
00178 close();
00179 copy(rhs);
00180 }
00181 return *this;
00182 }
00183
00184 protected:
00185 friend class ServerSocket;
00186 Socket(SOCKET sock, InetAddress inetAddress, in_port_t port);
00187 };
00188
00189 }
00190 }
00191
00192 #endif // IXE_io_Socket_H