SDLNet_TCP_Recv

Name

SDLNet_TCP_Recv -- get data from a connected socket

Synopsis

int SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen)

sock is a valid, connected, TCPsocket.

data is a pointer to the buffer that receives the data from sock.

maxlen is the maximum length (in bytes) that will be read.

Description

SDLNet_TCP_Recv gets available data that has been received on the socket. Up to maxlen bytes of data is read and stored in the location referenced by data. If no data has been received on the socket, this routine waits (blocks) until some comes in. The actual number of bytes copied into the location may be less than maxlen bytes.

A non-blocking way of using this function is to check the socket with SDLNet_CheckSockets and SDLNet_SocketReady and call SDLNet_TCP_Recv only if the socket is active.

Because of the behavior of TCP, a block of data sent by the peer will usually not be read at one time with SDLNet_TCP_Recv. TCP is a streaming protocol. This means that data will always be delivered in order, but not necessarily in the same chunks that it was sent. Applications that communicate with lines of text may need to call this routine several times and check for a newline character.

This routine is not used for server listening sockets.

Return Value

Returns the number of bytes received. A return value of -1 indicates an error. A return value of 0 indicates that the connection was closed by the peer.

Example

// receive some text from sock
//TCPsocket sock;
#define MAXLEN 1024
int result;
char msg[MAXLEN];

result = SDLNet_TCP_Recv(sock,msg,MAXLEN-1);
if(result <= 0) {
    // TCP Connection is broken. (because of error or closure)
    SDLNet_TCP_Close(sock);
    exit(1);
}
else {
    msg[result] = 0;
    printf("Received: \"%s\"\n",msg);
}

See Also

SDLNet_TCP_Send, SDLNet_TCP_Accept, SDLNet_TCP_Open, SDLNet_TCP_GetPeerAddress, SDLNet_TCP_Close, TCPsocket

SDLNet_TCP_Recv (last edited 2008-08-26 15:03:45 by ARennes-252-1-36-45)