PageRenderTime 35ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/c++/socket/socket.cpp

https://github.com/charlieyqin/development_misc
C++ | 249 lines | 164 code | 49 blank | 36 comment | 34 complexity | ad84e20d939ec3f0a3f9683f882e7dff MD5 | raw file
  1. /*
  2. Socket.cpp
  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. #include "Socket.h"
  20. #include <iostream>
  21. using namespace std;
  22. int Socket::nofSockets_= 0;
  23. void Socket::Start() {
  24. if (!nofSockets_) {
  25. WSADATA info;
  26. if (WSAStartup(MAKEWORD(2,0), &info)) {
  27. throw "Could not start WSA";
  28. }
  29. }
  30. ++nofSockets_;
  31. }
  32. void Socket::End() {
  33. WSACleanup();
  34. }
  35. Socket::Socket() : s_(0) {
  36. Start();
  37. // UDP: use SOCK_DGRAM instead of SOCK_STREAM
  38. s_ = socket(AF_INET,SOCK_STREAM,0);
  39. if (s_ == INVALID_SOCKET) {
  40. throw "INVALID_SOCKET";
  41. }
  42. refCounter_ = new int(1);
  43. }
  44. Socket::Socket(SOCKET s) : s_(s) {
  45. Start();
  46. refCounter_ = new int(1);
  47. };
  48. Socket::~Socket() {
  49. if (! --(*refCounter_)) {
  50. Close();
  51. delete refCounter_;
  52. }
  53. --nofSockets_;
  54. if (!nofSockets_) End();
  55. }
  56. Socket::Socket(const Socket& o) {
  57. refCounter_=o.refCounter_;
  58. (*refCounter_)++;
  59. s_ =o.s_;
  60. nofSockets_++;
  61. }
  62. Socket& Socket::operator=(Socket& o) {
  63. (*o.refCounter_)++;
  64. refCounter_=o.refCounter_;
  65. s_ =o.s_;
  66. nofSockets_++;
  67. return *this;
  68. }
  69. void Socket::Close() {
  70. closesocket(s_);
  71. }
  72. std::string Socket::ReceiveBytes() {
  73. std::string ret;
  74. char buf[1024];
  75. while (1) {
  76. u_long arg = 0;
  77. if (ioctlsocket(s_, FIONREAD, &arg) != 0)
  78. break;
  79. if (arg == 0)
  80. break;
  81. if (arg > 1024) arg = 1024;
  82. int rv = recv (s_, buf, arg, 0);
  83. if (rv <= 0) break;
  84. std::string t;
  85. t.assign (buf, rv);
  86. ret += t;
  87. }
  88. return ret;
  89. }
  90. std::string Socket::ReceiveLine() {
  91. std::string ret;
  92. while (1) {
  93. char r;
  94. switch(recv(s_, &r, 1, 0)) {
  95. case 0: // not connected anymore;
  96. // ... but last line sent
  97. // might not end in \n,
  98. // so return ret anyway.
  99. return ret;
  100. case -1:
  101. return "";
  102. // if (errno == EAGAIN) {
  103. // return ret;
  104. // } else {
  105. // // not connected anymore
  106. // return "";
  107. // }
  108. }
  109. ret += r;
  110. if (r == '\n') return ret;
  111. }
  112. }
  113. void Socket::SendLine(std::string s) {
  114. s += '\n';
  115. send(s_,s.c_str(),s.length(),0);
  116. }
  117. void Socket::SendBytes(const std::string& s) {
  118. send(s_,s.c_str(),s.length(),0);
  119. }
  120. SocketServer::SocketServer(int port, int connections, TypeSocket type) {
  121. sockaddr_in sa;
  122. memset(&sa, 0, sizeof(sa));
  123. sa.sin_family = PF_INET;
  124. sa.sin_port = htons(port);
  125. s_ = socket(AF_INET, SOCK_STREAM, 0);
  126. if (s_ == INVALID_SOCKET) {
  127. throw "INVALID_SOCKET";
  128. }
  129. if(type==NonBlockingSocket) {
  130. u_long arg = 1;
  131. ioctlsocket(s_, FIONBIO, &arg);
  132. }
  133. /* bind the socket to the internet address */
  134. if (bind(s_, (sockaddr *)&sa, sizeof(sockaddr_in)) == SOCKET_ERROR) {
  135. closesocket(s_);
  136. throw "INVALID_SOCKET";
  137. }
  138. listen(s_, connections);
  139. }
  140. Socket* SocketServer::Accept() {
  141. SOCKET new_sock = accept(s_, 0, 0);
  142. if (new_sock == INVALID_SOCKET) {
  143. int rc = WSAGetLastError();
  144. if(rc==WSAEWOULDBLOCK) {
  145. return 0; // non-blocking call, no request pending
  146. }
  147. else {
  148. throw "Invalid Socket";
  149. }
  150. }
  151. Socket* r = new Socket(new_sock);
  152. return r;
  153. }
  154. SocketClient::SocketClient(const std::string& host, int port) : Socket() {
  155. std::string error;
  156. hostent *he;
  157. if ((he = gethostbyname(host.c_str())) == 0) {
  158. error = strerror(errno);
  159. throw error;
  160. }
  161. sockaddr_in addr;
  162. addr.sin_family = AF_INET;
  163. addr.sin_port = htons(port);
  164. addr.sin_addr = *((in_addr *)he->h_addr);
  165. memset(&(addr.sin_zero), 0, 8);
  166. if (::connect(s_, (sockaddr *) &addr, sizeof(sockaddr))) {
  167. error = strerror(WSAGetLastError());
  168. throw error;
  169. }
  170. }
  171. SocketSelect::SocketSelect(Socket const * const s1, Socket const * const s2, TypeSocket type) {
  172. FD_ZERO(&fds_);
  173. FD_SET(const_cast<Socket*>(s1)->s_,&fds_);
  174. if(s2) {
  175. FD_SET(const_cast<Socket*>(s2)->s_,&fds_);
  176. }
  177. TIMEVAL tval;
  178. tval.tv_sec = 0;
  179. tval.tv_usec = 1;
  180. TIMEVAL *ptval;
  181. if(type==NonBlockingSocket) {
  182. ptval = &tval;
  183. }
  184. else {
  185. ptval = 0;
  186. }
  187. if (select (0, &fds_, (fd_set*) 0, (fd_set*) 0, ptval) == SOCKET_ERROR)
  188. throw "Error in select";
  189. }
  190. bool SocketSelect::Readable(Socket const* const s) {
  191. if (FD_ISSET(s->s_,&fds_)) return true;
  192. return false;
  193. }