void CSocket::WaitForConnetion()
{
CSocket* pSocket = NULL;
fd_set readfds;
readfds.fd_count = 1;
readfds.fd_array[0] = m_hSocket;
timeval timeout;
ZeroMemory(&timeout, sizeof(timeout));
timeout.tv_sec = 10;
while(!g_bQuit)
{
int iSelect = select(NULL, &readfds, NULL, NULL, &timeout);
if (iSelect == SOCKET_ERROR)
{
// error
break;
}
else
{
if (iSelect == 0)
{
// timeout
}
else
{
assert(iSelect == 1);
SOCKET new_sock = accept(m_hSocket, NULL, NULL);
if (new_sock != INVALID_SOCKET)
{
pSocket = new CSocketEx(new_sock);
// create a new thread to process the connection request with pSocket
}
}
continue;
}
}
您好,所有
CSocket是一个套接字包装器。
借助EJP的帮助。我修改了下面的代码。有错误吗?正如你所说,如果我通过关闭套接字句柄来使用方式,我必须将套接字句柄传递给另一个线程然后关闭它,对于不同线程中的操作符一个sokcet是否安全?
void CSocket::WaitForConnetion()
{
CSocket* pSocket = NULL;
timeval timeout;
ZeroMemory(&timeout, sizeof(timeout));
timeout.tv_sec = 10;
while(!g_bQuit)
{
fd_set readfds;
readfds.fd_count = 1;
readfds.fd_array[0] = m_hSocket;
int iSelect = select(NULL, &readfds, NULL, NULL, &timeout);
if (iSelect == SOCKET_ERROR)
{
// error
break;
}
else
{
if (iSelect == 0)
{
// timeout
}
else
{
assert(iSelect == 1);
SOCKET new_sock = accept(m_hSocket, NULL, NULL);
if (new_sock != INVALID_SOCKET)
{
pSocket = new CSocketEx(new_sock);
// create a new thread to process the connection request with pSocket
}
}
continue;
}
}