开发者

So what's the difference between these 2 ways of socket processing?

solution 1 deals with socket directly,while solution 2 first converts socket to fd,and then converts to fileno:

S 1:

maxfd = (sock_client > sock_server ) ? sock_client : sock_server;
FD_ZERO(&rfds);
FD_SET(sock_client, &rfds);
FD_SET(sock_server, &rfds);

if ((n = select(maxfd+1, &rfds, NULL, NULL, &timeout)) < 0)
...

S 2:

sockrfp = fdopen( sockfd, "r" );
sockwfp = fdopen( sockfd, "w" );

client_read_fd = fileno( stdin );
server_read_fd = fileno( sockrfp );
client_write_fd = fileno( stdout );
server_write_fd = fileno( sockwfp )


if ( client_read_fd >= server_read_fd )
    maxfd = client_read_fd;
else
    maxfd = server_read_fd;

FD_ZERO( &fdset );
FD_SET( client_read_fd, &fdset );
FD_SET( server_read_fd, &fdset );

if ((n = select(maxfd+1, &rfds, NULL, NULL, &timeout)) < 0)
...

What's t开发者_如何学编程he difference?Which is better?


S1 is correct. Functionally, both are same. S1 is direct and in S2, you just take a circuitous route to S1. fdopen followed by fileno yields the same where you started...

socket() or accept() gives you a file descriptor (fd). fdopen() on the socket fd yields you a FILE* (file pointer). fileno() on the file pointer yields you a file descriptor fd back. FILE* and fd are different ways of accessing the same internal structure (equivalent of open & fopen)

Sockets are bi-directional, you read and write to the same socket fd. In the second case, you have split the socket fd for read & write. IMO, call to socket should have read fdset & write fdset separate

[copied the comments into answer as sujjected by @y26jin]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜