BBS2chProxyRawSocket.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #ifdef _WIN32
  4. #include <winsock2.h>
  5. #include <windows.h>
  6. #define CLOSESOCKET(x) closesocket(x)
  7. #define SHUT_RDWR SD_BOTH
  8. #else
  9. #include <sys/socket.h>
  10. #define CLOSESOCKET(x) ::close(x)
  11. #endif
  12. #include "BBS2chProxyRawSocket.h"
  13. BBS2chProxyRawSocket::BBS2chProxyRawSocket(int sock) :
  14. socket(sock)
  15. {
  16. }
  17. BBS2chProxyRawSocket::~BBS2chProxyRawSocket()
  18. {
  19. }
  20. int BBS2chProxyRawSocket::read(char *buffer, int length)
  21. {
  22. return recv(socket, buffer, length, 0);
  23. }
  24. int BBS2chProxyRawSocket::readLine(char *buffer, int maxLength)
  25. {
  26. char *ptr = buffer;
  27. while (ptr < buffer + maxLength - 1) {
  28. int read = recv(socket, ptr, 1, 0);
  29. if (read != 1) {
  30. return 0;
  31. }
  32. if (*ptr++ == '\n') {
  33. break;
  34. }
  35. }
  36. *ptr = 0;
  37. return 1;
  38. }
  39. int BBS2chProxyRawSocket::write(const char *buffer, int length)
  40. {
  41. return send(socket, buffer, length, 0);
  42. }
  43. int BBS2chProxyRawSocket::writeString(const std::string &str)
  44. {
  45. return send(socket, str.data(), str.length(), 0);
  46. }
  47. void BBS2chProxyRawSocket::close(void)
  48. {
  49. if (socket >= 0) {
  50. shutdown(socket, SHUT_RDWR);
  51. #ifdef _WIN32
  52. Sleep(10);
  53. #else
  54. usleep(10000);
  55. #endif
  56. CLOSESOCKET(socket);
  57. socket = -1;
  58. }
  59. }