SocketUtils.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. streamUpdateIndex(out);
  11. while(left > 0)
  12. {
  13. int bytes = send(socket, data, left, MSG_NOSIGNAL);
  14. if(bytes == -1)
  15. {
  16. perror("Cannot send data");
  17. return -1;
  18. }
  19. left -= bytes;
  20. data += bytes;
  21. }
  22. return out->index;
  23. }
  24. int receiveAll(int socket, Stream* in)
  25. {
  26. int size = recv(socket, in->data, in->size, 0);
  27. if(size > 0)
  28. {
  29. int dataLength = streamGetIndex(in);
  30. if(size == dataLength)
  31. {
  32. in->size = dataLength;
  33. return dataLength;
  34. }
  35. streamEnsureCapacity(in, dataLength);
  36. in->size = dataLength;
  37. char* data = in->data + size;
  38. int left = dataLength - size;
  39. while(left > 0)
  40. {
  41. size = recv(socket, data, left, 0);
  42. if(size > 0)
  43. {
  44. data += size;
  45. left -= size;
  46. }
  47. else if(size == 0)
  48. {
  49. printf("Remote Socket closed\n");
  50. return -1;
  51. }
  52. else
  53. {
  54. perror("recv error");
  55. return -1;
  56. }
  57. }
  58. return dataLength;
  59. }
  60. else if(size == 0)
  61. {
  62. printf("Remote Socket closed\n");
  63. return 0;
  64. }
  65. else
  66. {
  67. perror("recv error");
  68. return -1;
  69. }
  70. return -1;
  71. }