使用TClientSocket使用阻塞式怎样防止连接错误

soloxiao 2005-12-26 08:15:55
现在有个连接用于即时通讯,比如中途网路断线后再取数据或发数据,会导致程序死掉
...全文
198 3 打赏 收藏 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
我不懂电脑 2005-12-26
  • 打赏
  • 举报
回复
阻塞方式的话,最好用多线程处理。死掉的原因可能是因为判断tcp错误需要一定的时间。
下面是一个用TWinSocketStream的例子:
The following example shows a typical ClientExecute method for a custom descendant of TServerClientThread. It reads from the socket connection specified by ClientSocket using a thread-local instance of TWinSocketStream.

void __fastcall TMyServerThread::ClientExecute(void)

{
TWinSocketStream *pStream;
char Buffer[10];
// make sure connection is active
while (!Terminated && ClientSocket->Connected)
{
try
{
Stream = new TWinSocketStream(ClientSocket, 60000);
try
{
memset(Buffer, 0, 10); // initialize the buffer
// give the client 60 seconds to start writing
if (pStream->WaitForData(60000))
{
if pStream->Read(Buffer, 10) == 0) // if can抰 read in 60 seconds

ClientSocket->Close(); // close the connection
// now process the request
...
}
else
ClientSocket->Close(); // if client doesn抰 start, close
}
__finally
{
delete pStream;
}
}
catch (Exception &E)
{
HandleException();
}
}
}
netsys2 2005-12-26
  • 打赏
  • 举报
回复
在读取数据时,先检查SOCKET有效性。

同时要处理SOCKET ERROR,如果发生错误,Socket->Close();
constantine 2005-12-26
  • 打赏
  • 举报
回复
try 拦截一下,如果有错误自己处理

1,317

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder 网络及通讯开发
社区管理员
  • 网络及通讯开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧