J
John paul coder
Guest
Hello All,
In my application I am using the socket and connect functions to connect to the server and establish the connection.
When establishing the connection to the server we are polling using while loop.
Can we avoid usage of polling? Is there any better option or improvement instead of using polling while establishing the socket connection?
Below is the code snippet:
int l_nresult = 0;
struct sockaddr_in saddr;
SOCKET l_hSocket;
int l_nPortNumber = -1;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr(SDK_IP_ADDRESS);
saddr.sin_port = htons((unsigned short)l_nPortNumber);
l_hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (l_hSocket == INVALID_SOCKET)
{
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
return false;
}
m_hSocket = l_hSocket;
l_nresult = connect(m_hSocket, (SOCKADDR*)&saddr, sizeof(saddr));
int l_nCount = 0;
while ((l_nresult == SOCKET_ERROR) && (l_nCount < 5))
{
l_nresult = connect(m_hSocket, (SOCKADDR*)&saddr, sizeof(saddr));
wprintf(L"In while loop Connect return error...");
l_nCount++;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
m_hConnectStatus = l_nresult;
if (l_nresult == SOCKET_ERROR)
{
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
closesocket(m_hSocket);
return false;
}
return true;
Continue reading...
In my application I am using the socket and connect functions to connect to the server and establish the connection.
When establishing the connection to the server we are polling using while loop.
Can we avoid usage of polling? Is there any better option or improvement instead of using polling while establishing the socket connection?
Below is the code snippet:
int l_nresult = 0;
struct sockaddr_in saddr;
SOCKET l_hSocket;
int l_nPortNumber = -1;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr(SDK_IP_ADDRESS);
saddr.sin_port = htons((unsigned short)l_nPortNumber);
l_hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (l_hSocket == INVALID_SOCKET)
{
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
return false;
}
m_hSocket = l_hSocket;
l_nresult = connect(m_hSocket, (SOCKADDR*)&saddr, sizeof(saddr));
int l_nCount = 0;
while ((l_nresult == SOCKET_ERROR) && (l_nCount < 5))
{
l_nresult = connect(m_hSocket, (SOCKADDR*)&saddr, sizeof(saddr));
wprintf(L"In while loop Connect return error...");
l_nCount++;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
m_hConnectStatus = l_nresult;
if (l_nresult == SOCKET_ERROR)
{
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
closesocket(m_hSocket);
return false;
}
return true;
Continue reading...