开发者

Android NDK - connect() blocks system

开发者 https://www.devze.com 2023-04-06 11:27 出处:网络
I\'m facing a wierd problem something can not explain ;) now i\'m developing client program working on the android phone.

I'm facing a wierd problem something can not explain ;)

now i'm developing client program working on the android phone. this app connects remote server and does something.

core library which's made in C++ (NDK) and Android UI works fine when using WIFI mode but system freezes when 3G data mode.

i got where this freezing causes, it was in connect() function.

the wierd thing is socket is already set NON-BLOCK mode before connect() line.

m_nSock = socket(AF_INET, SOCK_STREAM, 0);                        
if (m_nSock <= 0)                                                 
{   
    close(m_nSock);                                               
    return -1;                                                    
}                                                                 

flags = fcntl(m_nSock, F_GETFL, 0);                               
fcntl(m_nSock, F_SETFL, flags | O_NONBLOCK);                               

struct sockaddr_in AddrClient;
memset(&AddrClient, 0x00, sizeof(AddrClient));                    
AddrClient.sin_family = AF_INET;
AddrClient.sin_addr.s_开发者_如何学编程addr = inet_addr(szIP);                     
AddrClient.sin_port = htons(nPort);                               

nRet = connect(m_nSock, (struct sockaddr*)&AddrClient, sizeof(AddrClient));

blocking takes always about 21 seconds. (it may show default time is used somewhere in the kernel, i think.) how can i fix this? what should i search for?

any suggestion is welcome.

thanks in advance.


Try these changes:

put socket to non-blocking mode:

dword mode = 1;
ioctl(socket, FIONBIO, &mode);

back to blocking mode:

mode = 0;
ioctl(socket, FIONBIO, &mode);

This is how it works for me to set blocking mode


Your blocking code doesn't look right - you should be using F_SETFL as the command to set the flags. So:

int flags = fcntl(sock, F_GETFL);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
0

精彩评论

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