用TcpClient做通信的时候,经常发现网络连接不通的时候,代码就卡死在那里,TcpClient竟然没有超时的设定 泪奔啊 看来微软不是把所有工具准备得妥妥当当的啊
没办法 现在用线程来包装一下这个类 ,勉强可使用。
先上第一个类:这是网上的一种解决方案。
class TimeOutSocket
{
private static bool IsConnectionSuccessful = false;
private static Exception socketexception;
private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
public static TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
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(timeoutMiliSecond, 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();
}
}
}
插入第二种,自己实现的超时处理代码
static void Main(string[] args)
{
CancellationTokenSource c = new CancellationTokenSource();
CancellationToken token = c.Token; Task task = new Task(() =>
{
TcpClient client = new TcpClient(AddressFamily.InterNetwork);
client.SendTimeout = ;
client.ReceiveTimeout = ;
client.Connect(IPAddress.Parse("192.168.0.49"), int.Parse(""));
if (client.Connected)
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("AAAAABDEEKRJOWEQRIO@#$(*#@&%");
byte[] buffer = new byte[];
string responseData = string.Empty;
using (NetworkStream stream = client.GetStream())
{
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader Reader = new StreamReader(stream, encode);
Console.WriteLine("\nResponse stream received");
Char[] read = new Char[];
int count = ;
do
{
count = Reader.Read(read, , );
String str = new String(read, , count);
Console.Write(str);
} while (count > );
Reader.Close();
}
}
while (true)
{
if (token.IsCancellationRequested)
{
throw new OperationCanceledException();
}
}
}, token); task.Start();
if (task.Wait(, token))
{ }
else
{
c.Cancel();
Console.WriteLine("任务已经取消");
} }
OK,先写这么多吧