00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #if !defined(_xyzzy_socket_hxx_)
00022 # define _xyzzy_socket_hxx_
00023
00024 #include <sys/types.h>
00025 #include <sys/socket.h>
00026 #include <netinet/in.h>
00027 #include <netinet/ip.h>
00028 #include <arpa/inet.h>
00029 #include <stdlib.h>
00030 #include <string>
00031 #include "xyzzy/exception.hxx"
00032 #include "xyzzy/refcnt.hxx"
00033
00034 namespace xyzzy
00035 {
00036
00037 using namespace xyzzy;
00038 using std::string;
00039
00040 class TSocket
00041 {
00042 public:
00043 static const size_t cDfltSz = 1024;
00044
00045 class Exception : public TException
00046 {
00047 public:
00048 explicit Exception(const char *from);
00049
00050 const int m_errno;
00051
00052 virtual ~Exception();
00053
00054 private:
00055 const char* mkMessage(const char *from);
00056 };
00057
00058 class Connection : public TRcObj
00059 {
00060 public:
00061 explicit Connection(int id, size_t sz= cDfltSz);
00062
00068 const char* recv(ssize_t &nrd, bool nonBlocking = true)
00069 throw(Exception);
00070
00077 bool send(const void *buf, size_t len = 0, bool nonBlocking = true)
00078 throw(Exception);
00079
00080 virtual ~Connection();
00081
00082 private:
00083 const size_t m_cBufSz;
00084 char* mp_buf;
00085 int m_id;
00086 };
00087
00088 typedef PTRcObjPtr<Connection> TRcConnection;
00089
00090 virtual ~TSocket();
00091
00092 protected:
00093 explicit TSocket(u_int16_t port, string naddr = "127.0.0.1")
00094 throw(Exception);
00095
00096 const u_int16_t m_port;
00097 const string m_addr;
00098 int m_sockId;
00099 struct sockaddr_in m_sockAddr;
00100
00101 private:
00102 void init() throw(Exception);
00103 };
00104
00105 class TServerSocket : public TSocket
00106 {
00107 public:
00108 explicit TServerSocket(u_int16_t port, size_t bufSz = cDfltSz)
00109 throw(Exception);
00110
00111
00112 TRcConnection accept() throw(Exception);
00113
00114 virtual ~TServerSocket();
00115
00116 private:
00117 const size_t m_cBufSz;
00118 int m_sid;
00119 };
00120
00121 class TClientSocket : public TSocket
00122 {
00123 public:
00124 explicit TClientSocket(u_int16_t port, string naddr = "127.0.0.1",
00125 size_t bufSz = cDfltSz)
00126 throw(Exception);
00127
00133 const char* recv(ssize_t &nrd, bool nonBlocking = true)
00134 throw(Exception)
00135 {
00136 return m_conn->recv(nrd, nonBlocking);
00137 }
00138
00145 bool send(const void *buf, size_t len = 0, bool nonBlocking = true)
00146 throw(Exception)
00147 {
00148 return m_conn->send(buf, len, nonBlocking);
00149 }
00150
00151 virtual ~TClientSocket();
00152
00153 private:
00154 TRcConnection m_conn;
00155
00156 void init(size_t bufSz) throw(Exception);
00157 };
00158
00159 }
00160
00161 #endif