在socket中用accept怎么没有阻塞呢?如果做才能阻塞?(C代码) ( 积分: 100 )

  • 主题发起人 主题发起人 lncd
  • 开始时间 开始时间
L

lncd

Unregistered / Unconfirmed
GUEST, unregistred user!
原码如下:
void DoListen(int Port)
{
SOCKET ListenSocket;
SOCKET NewSocket ;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen;//=sizeof(ClientAddr);
int err;

//³õʼ»¯Socket¿â
if (SockInit() == false) return;

//´´½¨Socket
err = ListenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (err == SOCKET_ERROR)
{
printf("[0001-5] Socket´´½¨Ê§°Ü£¡/n");
return;
}
else
{
printf("[0001-6] Socket´´½¨³É¹¦£¡/n");
}

//ÉèÖ÷þÎñÆ÷µØÖ·ºÍ¶Ë¿Ú
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);

//°ó¶¨
err = bind(ListenSocket,(SOCKADDR*) &ServerAddr,sizeof(ServerAddr));
if (err == SOCKET_ERROR)
{
printf("[0001-7] Socket°ó¶¨Ê§°Ü£¡/n");
return;
}
else
{
printf("[0001-8] Socket°ó¶¨³É¹¦£¡/n");
}

//¼àÌý
err = listen(ListenSocket,5);
if (err == SOCKET_ERROR)
{
printf("[0001-9] Socket¼àÌýʧ°Ü£¡/n");
return;
}
else
{
printf("[0001-10] ¿ªÊ¼¼àÌý.../n");
}

bool WaitCon = true;
while(WaitCon)
{
NewSocket = accept(ListenSocket,(SOCKADDR*)&ClientAddr, &ClientAddrLen);
if (NewSocket != INVALID_SOCKET)
{
printf("¿Í»§¶Ë½¨Á¢ÁËÒ»¸öÁ¬½Ó£¡/n");
printf("ClientAddrLen=%d/n",ClientAddrLen);

¹Ø±Õн¨µÄsocket.
closesocket(NewSocket);
}
}

closesocket(ListenSocket);
SockOver();
}
 
原码如下:
void DoListen(int Port)
{
SOCKET ListenSocket;
SOCKET NewSocket ;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen;//=sizeof(ClientAddr);
int err;

//³õʼ»¯Socket¿â
if (SockInit() == false) return;

//´´½¨Socket
err = ListenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (err == SOCKET_ERROR)
{
printf("[0001-5] Socket´´½¨Ê§°Ü£¡/n");
return;
}
else
{
printf("[0001-6] Socket´´½¨³É¹¦£¡/n");
}

//ÉèÖ÷þÎñÆ÷µØÖ·ºÍ¶Ë¿Ú
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);

//°ó¶¨
err = bind(ListenSocket,(SOCKADDR*) &ServerAddr,sizeof(ServerAddr));
if (err == SOCKET_ERROR)
{
printf("[0001-7] Socket°ó¶¨Ê§°Ü£¡/n");
return;
}
else
{
printf("[0001-8] Socket°ó¶¨³É¹¦£¡/n");
}

//¼àÌý
err = listen(ListenSocket,5);
if (err == SOCKET_ERROR)
{
printf("[0001-9] Socket¼àÌýʧ°Ü£¡/n");
return;
}
else
{
printf("[0001-10] ¿ªÊ¼¼àÌý.../n");
}

bool WaitCon = true;
while(WaitCon)
{
NewSocket = accept(ListenSocket,(SOCKADDR*)&ClientAddr, &ClientAddrLen);
if (NewSocket != INVALID_SOCKET)
{
printf("¿Í»§¶Ë½¨Á¢ÁËÒ»¸öÁ¬½Ó£¡/n");
printf("ClientAddrLen=%d/n",ClientAddrLen);

¹Ø±Õн¨µÄsocket.
closesocket(NewSocket);
}
}

closesocket(ListenSocket);
SockOver();
}
 
后退
顶部