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

Categories

I want to simply connect to a server and get a response. My program is written in c++, and you can see the code here:

if((interpreterSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    return SOCKETERR;
}

fcntl(interpreterSocket, F_SETFD, FD_CLOEXEC);
setsockopt(interpreterSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof(flag));
setsockopt(interpreterSocket, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
setsockopt(interpreterSocket, SOL_SOCKET, SO_REUSEADDR , (char *) &flag, sizeof(flag));

address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(INTERPRETERADDR); 
address.sin_port = htons(INTERPRETERPORT);
adlen = sizeof(address);

if((rc = connect(interpreterSocket, (struct sockaddr *) &address, adlen)) < 0)
{
     close(interpreterSocket);
     return SOCKETERR;
}

The problem is when I run this program sometimes it has some trouble, so I have to kill the process. After that when I run the program, the connect function does not return and the program stops at the if line. I think this problem most be related to a socket that does not close in a proper manner.

I should mention that I run this program in CentOS.

Thanks in advance.

EDIT

I had one more problem, that caused the program stop at connect() function and it was some routing problems at the server.

See Question&Answers more detail:os

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

1 Answer

You are using blocking socket so connect blocks until it connects to server or timeout passes. To set sockets to non-blocking, you should use ioctlsocket function, exactly with FIONBIO command as second argument.

Remark that when you set sockets to non-blocking, you should start using select function to read or write to socket.

EDIT

Sorry, i forgot that's about Linux. It is possible to do nonblocking I/O on sockets by setting the O_NONBLOCK flag on a socket file descriptor using fcntl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...