Sachin Chourasiya Sachin Chourasiya - 3 months ago 23
C Question

Non Blocking Socket

A non blocking socket is the one where we call fcntl() method and associate the O_NONBLOCK flag with it. Can any one tell me what else is required to conver a normal TCP_IP socket into a non blocking socket?

What problems may arise if non-blocking sockets are made to work very well with Windows servers?

bua bua

Example init for linux may look like this:

int flags;
s = socket(PF_INET, SOCK_STREAM, IPPROTO_IP) // ret 5
setsockopt(s, SOL_TCP, TCP_NODELAY, [1], 4) 
setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, [1], 4) 
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, [1], 4) 
flags = fcntl(s,F_GETFL,0);
assert(flags != -1);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
connect(s, {sa_family=AF_INET, sin_port=htons(5001), sin_addr=inet_addr("")}, 16)

Basic white paper from sun:

sun asych net

On windows You use Overlapped IO sockets to get non blocking networking.

Look here and in MSDN how to write code with OVERLAPPED structures

On Linux use epoll().

On solaris socket().

Be aware to read or write to a socket when it's not ready. (select-output) Because You may receive EAGAIN error.

Great cross platform library (but C++ and new c++ standard candidate) is boost::asio.

It uses native system asynchronous methods.