My C + + server records----Socket read operations that are not blocked

Source: Internet
Author: User

One of the basic operations on the server side is to read data from the socket's FD, which is the read function we often use.
Welcome to follow my server code: http://code.taobao.org/p/fastServer/src/

Today is mainly concerned with the correct conduct of the read operation
Prime Minister, my socket is a non-blocking property that has been set. The read function encounters different errno when non-blocking reads the FD.
How to properly handle these erron states?

1.errno == EAGAIN

该错误返回码主要是,当我们使用了    以 O_NONBLOCK的标志打开文件操作符,因为是非阻塞,我们不停的进行read操作,就会有没有数据可读的情况,此时,程序并不会阻塞起来等待数据,准备数据返回,而是read函数返回一个错误,EAGAIN。就是提示程序没有数据可读了,请稍后 再试。也就是我们继续recv操作。

2.errno==EINTR

This error, primarily the error description of interrupted system call, should also continue.

3. When our read function returns 0, it indicates that the link has been disconnected. We should close this link at this time, that is, call the close operation

Here is a read process that we should compare the standard use of, the following code

intNread,nread = Read (FD, BUF,1024x768);if(Nread = =-1) {if(errno = = Eagain | | errno = = EINTR) {nread =0; }Else{Close(FD);return; }}Else if(Nread = =0) {Close(FD);return;}if(nread) {///The buff has been disposed of. Therefore, just follow the above code to properly handle FD, or set a layer of loops can be. The data can be read correctly. For more articles, please visit http://blog.csdn.net/wallwindMy Code directory: http://code.taobao.org/u/wallwind/mypro/Learn from each other and communicate with each other

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

My C + + server records----Socket read operations that are not blocked

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.