1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <stdio.h>
- #include "SocketUtils.h"
- #include "Stream.h"
- int sendAll(int socket, Stream* out)
- {
- char* data = out->data;
- int left = out->index;
- while(left > 0)
- {
- int bytes = send(socket, data, left, MSG_NOSIGNAL);
- if(bytes == -1)
- {
- perror("Cannot send data");
- return -1;
- }
- left -= bytes;
- data += bytes;
- }
- return out->index;
- }
- int receiveAll(int socket, Stream* in)
- {
- int pos = in->index;
- int capacity = in->capacity - pos;
- int size = recv(socket, in->data + pos, capacity, 0);
- if(size > 0)
- {
- in->size = pos + size;
- if(size < capacity)
- {
- return size;
- }
- while(size == capacity)
- {
- // more data must be read
- streamEnsureIndex(in, in->capacity * 2 - 1);
-
- pos += size;
- capacity = in->capacity - pos;
- size = recv(socket, in->data + pos, capacity, MSG_DONTWAIT);
- if(size <= 0)
- {
- size = 0;
- break;
- }
- in->size += size;
- if(size < capacity)
- {
- break;
- }
- }
- pos += size;
- return pos - in->index;
- }
- else if(size == 0)
- {
- printf("Remote Socket closed\n");
- return 0;
- }
- else
- {
- perror("recv error");
- return -1;
- }
- return -1;
- }
|