Beej's Guide Network to Programming series serialization 14

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.