Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

c - 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 convert 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("192.168.0.68")}, 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.

boost::asio


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...