SocketUtils.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <stdio.h>
  4. #include "SocketUtils.h"
  5. #include "Stream.h"
  6. int sendAll(int socket, Stream* out)
  7. {
  8. char* data = out->data;
  9. int left = out->index;
  10. while(left > 0)
  11. {
  12. int bytes = send(socket, data, left, MSG_NOSIGNAL);
  13. if(bytes == -1)
  14. {
  15. perror("Cannot send data");
  16. return -1;
  17. }
  18. left -= bytes;
  19. data += bytes;
  20. }
  21. return out->index;
  22. }
  23. int receiveAll(int socket, Stream* in)
  24. {
  25. int pos = in->index;
  26. int capacity = in->capacity - pos;
  27. int size = recv(socket, in->data + pos, capacity, 0);
  28. if(size > 0)
  29. {
  30. in->size = pos + size;
  31. if(size < capacity)
  32. {
  33. return size;
  34. }
  35. while(size == capacity)
  36. {
  37. // more data must be read
  38. streamEnsureIndex(in, in->capacity * 2 - 1);
  39. pos += size;
  40. capacity = in->capacity - pos;
  41. size = recv(socket, in->data + pos, capacity, MSG_DONTWAIT);
  42. if(size <= 0)
  43. {
  44. size = 0;
  45. break;
  46. }
  47. in->size += size;
  48. if(size < capacity)
  49. {
  50. break;
  51. }
  52. }
  53. pos += size;
  54. return pos - in->index;
  55. }
  56. else if(size == 0)
  57. {
  58. printf("Remote Socket closed\n");
  59. return 0;
  60. }
  61. else
  62. {
  63. perror("recv error");
  64. return -1;
  65. }
  66. return -1;
  67. }