我做了一个软件要使用到socket 通信的,在执行
try
{
//尝试连接
socket.Connect(hostEP);
}
catch (Exception ce)
{
MessageBox("无法远程连接到服务器,请稍后重试");
return ce.Message;
}
发现当远程主机存在时,并且开了监听端的话,是没有问题的,当远程主机存在。但是未开监听软件时,那么差不多要等5分多钟才会出现“无法远程连接到服务器,请稍后重试”这个错误,这个过程相当的漫长,所以想找一个方法看能不能设置一下响应时间。连不上马上报错。
我到网上找了一下有以下代码说是可以解决:
class TimeOutSocket
{
private static bool IsConnectionSuccessful = false;
private static Exception socketexception;
private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{
TimeoutObject.Reset();
socketexception = null;
string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMSec, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
throw new TimeoutException("TimeOut Exception");
}
}
private static void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
}
用了以后发现在windows mobile环境里没有tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient);这个事件,我转到winfrom环境下却是有的,这下真的没有办法了。
还有一个朋友说直接用一个计时器设置,多少秒,然后到了时间直接socket.Close();觉得这个方法也不太好。占用了系统内存。因为智能机的内存就那么点大,只能尽量的减少内存的占用量。
朋友们有什么好的方法告知一下呀,谢谢!!
我的环境是windows mobile 5.0 ntf2.0 C#
------解决方案--------------------
LZ可以试下用线程池等待函数:
http://www.cnblogs.com/sql4me/archive/2009/04/29/1446080.html
------解决方案--------------------
mobile上可以通过select函数来设置超时。
比如:
tv.tv_sec = 1;
tv.tv_usec = 0;
// Initialize the fd_set structure to NULL
FD_ZERO (&fds);
// Add the sckServer socket to fd_set structure
FD_SET (sckServer, &fds);
// Call the select command
if (select(0, &fds, NULL, NULL, &tv) == 0)
// Maximum wait time is expired.
continue;
------解决方案--------------------