Fast HTTP download, need a little help
Hello, I am using a Winsock DLL made specialy fro BlitzBasic.
In the dll there is a function called tcpconnect, and it looks like this :
Code:
//////////////////////////////////////////////////////////////////////////////////////////////
bool CSocket::tcpconnect(char *address, int port, int mode)
{
SOCKADDR_IN addr;
LPHOSTENT hostEntry;
sockid = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
u_long i = 1;
ioctlsocket(sockid, FIONBIO,&i);
if((hostEntry = gethostbyname(address))==NULL)
{
closesocket(sockid);
return false;
}
addr.sin_family = AF_INET;
addr.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
addr.sin_port = htons((u_short)port);
connect(sockid, (LPSOCKADDR)&addr, sizeof(SOCKADDR_IN));
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
I am using this to conect to a website and download a page (html page).
I tested this function for about 100 websites, and on most websites it takes 0.001 seconds to connect, but on other websites, it takes even 0.3 seconds to connect.
I don't have a problem if the connection takes to long, but the problem is that by calling tcpconnect (from the DLL), if the connection is not instant, it hangs the program until it connects .
I also have a function tcpconnected(tcpid) that checks if a tcp is connected.
What should I modify in tcpconnect function from above, so that it automaticaly returns true, without any lags. I will check later one if it's connected.
I made a little reasearch and I noticed that I should make the socket async.
I am using the folowing code for tcp connect now :
Code:
bool CSocket::tcpconnect(char *address, int port, double h)
{
SOCKADDR_IN addr;
LPHOSTENT hostEntry;
HWND hwin;
hwin=(HWND)(int)h;
sockid = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
WSAAsyncSelect (sockid, hwin, 1045, FD_READ | FD_CONNECT | FD_CLOSE);
hostEntry = gethostbyname(address);
addr.sin_family = AF_INET; //family
addr.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list); //server ip
addr.sin_port = htons((u_short)port); //set port
connect(sockid, (SOCKADDR *)&addr, sizeof(addr));
return true;
}
I noticed that the only problem (hang) is with connect function.
If I remove it, the function tcpconnect is executed in about 0,001 seconds.
If I enable it, the same problem, sometimes it taes 0,02 seconds, sometimes 0,4.
Of course, I can't connect to the server if I don't use the connect function. So is there an alternative ?
How can I make this function be executed instantly, and as I sayed, I will check with another function if the connection is established.
Can someone help ?
Thank you