1.创建socket默认为阻塞。一下一段小程序,给定的是跨平台window和linux,设置socket为阻塞模式
void SetSocketUnBlock(SOCKET hSocket)
{
#ifdef WIN32
u_long mode = 1;
if (SOCKET_ERROR == ioctlsocket(hSocket, (long)FIONBIO, &mode)) //非阻塞,异步模式。
//允许或禁止套接口s的非阻塞模式。argp指向一个无符号长整型,如允许非阻塞模式则非零,如禁止非阻塞模式则为零。
{
COM_ASSERT(0); // coding error checking
return;//lint !e527 ignored the unreachable warning
}
#else
int iGetFL = fcntl(hSocket, F_GETFL);//linux下,设置非阻塞,异步模式
if (-1 == iGetFL)
{
COM_ASSERT(0);
return;
}
if (-1 == fcntl(hSocket, F_SETFL, iGetFL | O_NONBLOCK))
{
COM_ASSERT(0);
return;
}
#endif
}
详细说明,可参考ioctlsocket(),fcntl()
---------------------------------------------------------------------------------
2.设置socket为非阻塞模式
void SetSocketBlock(SOCKET hSocket)
{
#ifdef WIN32
u_long mode = 0;
if (SOCKET_ERROR == ioctlsocket(hSocket, (long)FIONBIO, &mode))
{
COM_ASSERT(0); // coding error checking
return; //lint !e527 ignored the unreachable warning
}
#else
int iGetFL = fcntl(hSocket, F_GETFL);
if (-1 == iGetFL)
{
COM_ASSERT(0);
return;
}
if (-1 == fcntl(hSocket, F_SETFL, iGetFL & (~O_NONBLOCK)))
{
COM_ASSERT(0);
return;
}
#endif //! END WIN32
}