Several Functions frequently used in socket communication and their related descriptions:
1: ssize_t write (int fd, const void * buff, size_t nbytes). The parameter description is omitted. If the function fails to return-1 and the error variable is set, we can handle the error according to the error type. If errno is eintr, it indicates an error is interrupted. At this time, we can continue to write data.
(In addition, we can't do anything about it ). Success can be divided into two types: the return value must be equal to the value of nbytes during full write; while loop (condition: whether the return value is smaller than nbytes) can be used for full write.
. The following is an example:
Int my_write (int fd, void * buffer, int length)
{
Int bytes_left;
Int written_bytes;
Char * PTR;
PTR = buffer;
Bytes_left = length;
While (bytes_left> 0)
{
/* Start writing */
Written_bytes = write (FD, PTR, bytes_left );
If (written_bytes <= 0)/* Error */
{
If (errno = eintr)/* interrupt error we continue to write */
Written_bytes = 0;
Else/* No other errors, so I had to retreat */
Return (-1 );
}
Bytes_left-= written_bytes;
PTR + = written_bytes;/* continue writing from the rest */
}
Return (0 );
}
2: The principle and usage of the READ function are the same as that of the write function. related examples are as follows:
Int my_read (int fd, void * buffer, int length)
{
Int bytes_left;
Int bytes_read;
Char * PTR;
Bytes_left = length;
While (bytes_left> 0)
{
Bytes_read = read (FD, PTR, bytes_read );
If (bytes_read <0)
{
If (errno = eintr)
Bytes_read = 0;
Else
Return (-1 );
}
Else if (bytes_read = 0)
Break;
Bytes_left-= bytes_read;
PTR + = bytes_read;
}
Return (length-bytes_left );
}
3: The send/Recv function provides the same functions as the write/read function. You can add one more parameter (the default value is 0). The function prototype is as follows:
Int Recv (INT sockfd, void * Buf, int Len, int flags)
Int send (INT sockfd, void * Buf, int Len, int flags)
4: setsockopt function. This function is generally used to set the relevant attributes of sock_fd. Example:
Setsockopt (sock_fd, sol_socket, so_sndbuf, (const char *) & nsendbuf, sizeof (INT) -- set the size of the _fd sending buffer. Similarly, you can set the accept buffer size.