PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/Socket.h

https://github.com/chaoswork/httpServer
C Header | 76 lines | 49 code | 15 blank | 12 comment | 0 complexity | 795d623273c2388c4f2fd3e64a701f9e MD5 | raw file
  1. #ifndef SOCKET_H
  2. #define SOCKET_H
  3. #ifndef PACKAGE_H
  4. #include "package.h"
  5. #endif
  6. #include <string>
  7. #include <string.h>
  8. #ifdef linux
  9. #include <sys/socket.h>
  10. #include <netinet/in.h>
  11. #include <arpa/inet.h>
  12. #include <netdb.h>
  13. #include <sys/types.h>
  14. #include <unistd.h>
  15. typedef int SOCKET;
  16. typedef void* optval_t;
  17. #else //WIN32
  18. #include <winsock2.h>
  19. #include <Ws2tcpip.h>
  20. #pragma comment(lib,"WS2_32.lib")
  21. //typedef unsigned int socklen_t;
  22. typedef const char* optval_t;
  23. #endif
  24. #ifndef ERROR_H
  25. #include "error.h"
  26. #endif
  27. #include "SocketStream.h"
  28. CW_BEGIN
  29. using std::string;
  30. /* Socket is class to handle socket,can't copy publicly.
  31. * With the action connect,close,and server action bind,
  32. * listen and accept.
  33. * I tried to make it Exception safety and thread safe and
  34. * cross linux and windows platform.*/
  35. class Socket{
  36. public:
  37. explicit Socket(SOCKET sk=-1);
  38. Socket(int af,int type,int protocol=0);
  39. virtual ~Socket();
  40. void connect(const string& ipAddr,unsigned short port);
  41. /* bind,listen and accept should used for server*/
  42. void bind(unsigned short port);
  43. void listen(int backlog);
  44. //Socket accept(struct sockaddr_in* cliAddr=0);
  45. void accept(Socket& SK,struct sockaddr_in* cliAddr=0);
  46. void close();
  47. /* Socket i/o stream */
  48. SocketStream getSocketStream();
  49. protected:
  50. void create(int af,int type,int protocol=0);
  51. /* accept return a Socket Object,so we make the copy constructor
  52. * as private,and also disallow the operator= used public*/
  53. Socket(const Socket& SK){m_socket=SK.m_socket;}
  54. Socket& operator=(const Socket&);
  55. private:
  56. //SOCKET m_socket;
  57. int m_socket;
  58. bool socketClosed;
  59. };
  60. CW_END
  61. #endif /*SOCKET_H*/