【发布时间】:2018-12-12 03:07:11
【问题描述】:
我想用NDK在Android中创建一个socket,但是连接服务器时有时会出错,我可以确保用户手机的网络是可用的。
一种情况是超时错误,另一种似乎是连接被拒绝,因为我得到以下日志,我认为第二个错误是连接被拒绝,因为来自getsockopt 的错误是 111,即使 strerror 给我操作正在进行中,但服务器地址有效:
connect::socket error: Operation now in progress
Or
connect::error:111, Operation now in progress
这是我的代码 sn-p:
bool connect(int sockfd, struct sockaddr *address, socklen_t address_len, int timeout) {
int ret = 0;
struct timeval tv;
fd_set mask;
// set socket non block
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
// use select to check socket connection
ret = connect(sockfd, address, address_len);
if (-1 == ret) {
if (errno != EINPROGRESS) {
perror("connect");
inetConnectFailCode = errno;
LOG(TAG.c_str(), "connect::errno != EINPROGRESS: %s", strerror(errno));
return false;
}
LOG(TAG.c_str(), "connecting...\n");
FD_ZERO(&mask);
FD_SET(sockfd, &mask);
tv.tv_sec = timeout;
tv.tv_usec = 0;
if (select(sockfd + 1, NULL, &mask, NULL, &tv) > 0) {
int error = 0;
socklen_t tmpLen = sizeof(int);
int retopt = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &tmpLen);
if (retopt != -1) {
if (0 == error) {
LOG(TAG.c_str(), "has connect");
return true;
} else {
//I get error here
LOG(TAG.c_str(), "connect::error:%d, %s", error, strerror(errno));
return false;
}
} else {
LOG(TAG.c_str(), "connect::socket error:%d", error);
return false;
}
} else {
//timeout, and I get error here sometimes
LOG(TAG.c_str(), "connect::socket error: %s", strerror(errno));
return false;
}
}
LOG(TAG.c_str(), "has connect");
return true;
}
这个问题困扰了我好久,有大神可以帮帮我,谢谢。
【问题讨论】: