BBS2chProxyRawSocket.cpp 1.1 KB

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