PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/c++/socket/socket.h

https://github.com/charlieyqin/development_misc
C Header | 99 lines | 44 code | 24 blank | 31 comment | 0 complexity | 55ae8ec487ce37d25ba26712069708e0 MD5 | raw file
  1. /*
  2. Socket.h
  3. Copyright (C) RenĂŠ Nyffenegger
  4. This source code is provided 'as-is', without any express or implied
  5. warranty. In no event will the author be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this source code must not be misrepresented; you must not
  11. claim that you wrote the original source code. If you use this source code
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original source code.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. RenĂŠ Nyffenegger rene.nyffenegger@adp-gmbh.ch
  18. */
  19. #ifndef SOCKET_H
  20. #define SOCKET_H
  21. #include <WinSock2.h>
  22. #include <string>
  23. enum TypeSocket {BlockingSocket, NonBlockingSocket};
  24. class Socket {
  25. public:
  26. virtual ~Socket();
  27. Socket(const Socket&);
  28. Socket& operator=(Socket&);
  29. std::string ReceiveLine();
  30. std::string ReceiveBytes();
  31. void Close();
  32. // The parameter of SendLine is not a const reference
  33. // because SendLine modifes the std::string passed.
  34. void SendLine (std::string);
  35. // The parameter of SendBytes is a const reference
  36. // because SendBytes does not modify the std::string passed
  37. // (in contrast to SendLine).
  38. void SendBytes(const std::string&);
  39. protected:
  40. friend class SocketServer;
  41. friend class SocketSelect;
  42. Socket(SOCKET s);
  43. Socket();
  44. SOCKET s_;
  45. int* refCounter_;
  46. private:
  47. static void Start();
  48. static void End();
  49. static int nofSockets_;
  50. };
  51. class SocketClient : public Socket {
  52. public:
  53. SocketClient(const std::string& host, int port);
  54. };
  55. class SocketServer : public Socket {
  56. public:
  57. SocketServer(int port, int connections, TypeSocket type=BlockingSocket);
  58. Socket* Accept();
  59. };
  60. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_2tiq.asp
  61. class SocketSelect {
  62. public:
  63. SocketSelect(Socket const * const s1, Socket const * const s2=NULL, TypeSocket type=BlockingSocket);
  64. bool Readable(Socket const * const s);
  65. private:
  66. fd_set fds_;
  67. };
  68. #endif