关于阻塞式TCPClient线程中止问题,急!(50分)

  • 主题发起人 主题发起人 PMA
  • 开始时间 开始时间
P

PMA

Unregistered / Unconfirmed
GUEST, unregistred user!
[:(]用BCB编程,采用TCP Client与对方的TCP Server通讯,每个端口对应一个线程。如果开的线程2个以下,没有什么问题,如果开50个以上,并且通讯条件不太稳
定的情况下,运行20分钟后常会有线程中断。跟踪发现好像是在open()或Send()的时候返不回来。现在用的是阻塞模式。轻大家帮忙看看问题何在,如何解决?
谢谢!!源代码如下
BOOL TKHTCPComm::Open()
{
DWORD dwError;

char szTmp[100] ;
hostent* he;
int addr;
in_addr in;
int i;
IsOpening = true;
if( !InitFlag )
{
if (WSAStartup(MAKEWORD(2,0),&WSAData) )
{
WSACleanup();

return false;
}
else
InitFlag = true ;
}

to.sin_family = AF_INET;
to.sin_port = htons((unsigned short )RemotePort);
if(FRemoteHost != ""
&& FRemoteIP == "127.0.0.1"
)
{
he = gethostbyname(FRemoteHost.c_str());
memcpy( &addr, he->h_addr_list[0],sizeof(int));
to.sin_addr.s_addr = addr ;
FRemoteIP = inet_ntoa( to.sin_addr ) ;
}
else
to.sin_addr.s_addr = inet_addr(RemoteIP.c_str());
sockfd=socket(AF_INET,SOCK_STREAM,0);

if (sockfd==INVALID_SOCKET)
{
goto exitfail;
}

if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(char FAR*)&optval,
sizeof(optval))==SOCKET_ERROR)
{
goto exitfail;
closesocket(sockfd);
return FALSE;
}
ZeroMemory(&server,sizeof(struct sockaddr_in));
server.sin_family=AF_INET;
server.sin_port= htons(RemotePort);
server.sin_addr.s_addr = inet_addr ( FRemoteIP.c_str() );//TCP
if( connect( sockfd , (sockaddr*)&server ,sizeof( server ) ) ==-1 )
{
goto exitfail;
}
if( LocalPort == 0 )
{
int len1,len = sizeof( server );
if( len1 = getsockname( sockfd,(sockaddr*)&server,&len))
{
}
LocalPort = htons( server.sin_port );
}
wasEvent = WSACreateEvent();
if ( WSAEventSelect(sockfd, wasEvent, FD_READ|FD_CLOSE) == SOCKET_ERROR)
{
WSACloseEvent(wasEvent);

closesocket(sockfd);
sockfd = NULL ;

return FALSE;
}
event[0] = wasEvent ;
ConnectFlag = TRUE;
IsOpening = false;
Resume();
Sleep(100);

if( Suspended ) Resume();

return true ;

exitfail:
try
{
i = WSAGetLastError();
closesocket(sockfd);
}
catch(...)
{
i = 1;
}
IsOpening = false ;
ConnectFlag = 0;
return false;
}

发送的源代码如下:
int TKHTCPComm::Send(char *buf,int len)
{
int r;
DWORD dwError;
hostent* he;
int addr;
r = -1;
to.sin_family = AF_INET;
to.sin_port = htons((unsigned short )RemotePort);
if(FRemoteHost != ""
&& FRemoteIP == "127.0.0.1"
)
{
he = gethostbyname(FRemoteHost.c_str());
memcpy( &addr, he->h_addr_list[0],sizeof(int));
to.sin_addr.s_addr = addr ;
FRemoteIP = inet_ntoa( to.sin_addr ) ;
}
else
to.sin_addr.s_addr = inet_addr(RemoteIP.c_str());

if (ConnectFlag)
{
r = sendto (sockfd, buf, len, 0, (struct sockaddr FAR *)&to, sizeof(SOCKADDR));
if (r == SOCKET_ERROR)
{
dwError = WSAGetLastError();
Close();

}
}
return r;
}
 
[:(]没有人知道吗 ?
就是进入connect或send()后出不来了,导致线程中止!怎么解决呀 ?!
 
后退
顶部