Previous: http://www.bkjia.com/kf/201112/115526.html
5.7. send () and recv () --- talk to me, baby!
These two functions are used for communication between Stream sockets or datagram sockets.
Send () function prototype:
Int send (intsockfd, const void * msg, int len, int flags );
Sockfd is the socket descriptor that you want to send data (or the socket () is called or returned by accept .) Msg is a pointer to the data you want to send. Len is the length of data. Set flags to 0. (For more information, see the man page of send ).
The following is some sample code:
Char * msg = "Beejwas here !";
Int len, bytes_sent;
.
.
.
Len = strlen (msg );
Bytes_sent = send (sockfd, msg, len, 0 );
.
.
.
Send () returns the number of bytes of actually sent data -- it may be smaller than the number you requested to send! Note: Sometimes you tell it to send a bunch of data, but it cannot be processed successfully. It only sends data that it may send, and then hopes that you can send other data. Remember, if the data returned by send () does not match len, you should send other data. But there is also good news: if the package you want to send is small (less than 1 K), it may process the data to be sent once. In the end, it returns-1 in case of an error and sets errno.
Recv () function prototype:
Int recv (intsockft, void * buf, int len, int flags );
Sockfd is the socket descriptor to be read. Buf is the buffer of the information to be read. Len is the maximum buffer length. Flags can be set to 0. (See the man page of recv .) Recv () returns the number of bytes that actually read the buffered data. Or return-1 in case of an error and set errno.
It's easy, isn't it? You can now send and receive data on a streaming socket. You are now a Unix Network programmer!
From the column xiaobin_HLJ80