工作在同步阻塞模式下socket连接,当有客户端连接进来时,如果是有效的客户端,在连接后
回立刻发送一个11位的手机号码,判断出连接的客户端不是合法的就把刚才分配的socket连接释放。
程序如下:(线程的run中处理)
int mSocket::Run() 
{
// TODO: Add your specialized code here and/or call the base class
char buff[12],telnum[12];
CSize size;
size.cx=0;
size.cy=30;
int s,Route,tellen;
SOCKET Clientsock; Route=0; CFrameWnd* pFrameWnd;
CRectvinfoView * RealView;
pFrameWnd = (CFrameWnd *)theApp->m_pMainWnd;
RealView = (CRectvinfoView *)pFrameWnd->GetActiveFrame()->GetActiveView(); while(Loop)
{

s=1;
SOCKET sockclient;
sockclient=accept(ServSock,(sockaddr*)&(SockAddr),&(addlen)); 
Route = theApp->getcount();
if (Route<0)
continue;
theApp->SetSocket(Route,sockclient);    
PromptInfo = new UCHAR[10];
if (theApp->GetSocket(Route)==INVALID_SOCKET)
{
strcpy((char*)PromptInfo,"连接错误!");
theApp->SetSocket(Route,NULL);
::PostMessage(theApp->frameWnd,DSPLAYSTATUSBAR,WPARAM(1),LPARAM(PromptInfo));
}
else
{

theApp->IncreaseConnectedNum();
strcpy((char*)PromptInfo,"连接成功!");

::PostMessage(theApp->frameWnd,DSPLAYSTATUSBAR,WPARAM(1),LPARAM(PromptInfo));
::PostMessage(theApp->frameWnd,DSPLAYSTATUSBAR,WPARAM(3),LPARAM(theApp->GetConnectedNum()));

Clientsock= theApp->GetSocket(Route);
tellen = 0;
telnum[0] = 0;

while((s!=SOCKET_ERROR)&&(s!=0)&&(tellen<11))
{
s=recv(Clientsock,buff,11,0); //有效客户端会在连接后发送11位的手机号码
if ((s!=SOCKET_ERROR)&&(s>0))
{
if (s>11) s=11;
if ((s+tellen) > 11)
s = 11 - tellen;
buff[s]=0;
tellen += s;
strcat(telnum,buff);
}
}

if (tellen>=11)
{
theApp->SetSocketTel(Route,telnum);    
RealView->AddListId(telnum);
}
else  //非合法的有效客户端应释放分配的socket连接
{
if (s==SOCKET_ERROR)
send(theApp->GetSocket(Route),"Disconnected++++++",100,0);
shutdown(theApp->GetSocket(Route),2);
closesocket(theApp->GetSocket(Route));
theApp->SetSocket(Route,NULL);
theApp->DecreaseConnectedNum();
::PostMessage(theApp->frameWnd,DSPLAYSTATUSBAR,WPARAM(3),LPARAM(theApp->GetConnectedNum()));
}
}

}
return CWinThread::Run();
}
问题是当有非合法性的客户端连接进来后while((s!=SOCKET_ERROR)&&(s!=0)&&(tellen<11))
{
s=recv(Clientsock,buff,11,0);
if ((s!=SOCKET_ERROR)&&(s>0))
{
if (s>11) s=11;
if ((s+tellen) > 11)
s = 11 - tellen;
buff[s]=0;
tellen += s;
strcat(telnum,buff);
}
}
}
在s=recv(Clientsock,buff,11,0)便会阻塞在这里而不能将刚刚分配的socket连接释放,如何才能解决这个问题

解决方案 »

  1.   

    socket有阻塞和非阻塞模式的阻塞模式下如果没有数据来那就会一直等数据的到来
      

  2.   

    将socket设定为非阻塞方式就可以解决这个问题^_^//设置非阻塞方式连接
    unsigned long ul = 1;
    ret = ioctlsocket(cClient, FIONBIO, (unsigned long*)&ul);
    if(ret==SOCKET_ERROR)return 0;
      

  3.   

    设置成非阻塞方式时:sockclient=accept(ServSock,(sockaddr*)&(SockAddr),&(addlen)); 这里也不会阻塞,怎么识别什么时候有客户端连接进来了呢?还有对于非阻塞方式的连接能不能才用同步模式