public static string Connection() { string MesssageNotice = ""; CancellationTokenSource c = new CancellationTokenSource(); CancellationToken token = c.Token; Task<string> task = new Task<string>(() => { try { token.ThrowIfCancellationRequested(); TcpClient client = new TcpClient(AddressFamily.InterNetwork); client.SendTimeout = 3000; client.ReceiveTimeout = 3000; client.Connect(IPAddress.Parse("XXXX.XXX.XXXX.XXX"), int.Parse("456")); if (client.Connected) { Byte[] data = System.Text.Encoding.UTF8.GetBytes("ABCDEFGDSGFWEREW"); using (NetworkStream stream = client.GetStream()) { stream.Write(data, 0, data.Length); data = new Byte[client.ReceiveBufferSize]; string responseData = string.Empty; int bytes = stream.Read(data, 0, data.Length); responseData = Encoding.UTF8.GetString(data, 0, bytes); client.Close(); stream.Close(); MesssageNotice = responseData; return MesssageNotice; } } else { token.ThrowIfCancellationRequested(); c.Cancel(); MesssageNotice = "failed"; return MesssageNotice; } } catch (SocketException) { token.ThrowIfCancellationRequested(); c.Cancel(); //throw; throw new Exception("failed"); } catch (Exception) { token.ThrowIfCancellationRequested(); c.Cancel(); throw; } }, token); task.Start(); if (task.Wait(3000, token)) { return task.Result; } else { c.Cancel(); return "failed"; } }
有的时候 服务器 不会立马将数据返回……
我加了3秒的等待,
为什么 我写的超时就取消不管用,过了 50-60秒,代码还会跳转到
全部贴出来看看呗,你说的超时处理,没看到。
而且我可以告诉你,你这段还有隐患
Byte[] data = System.Text.Encoding.UTF8.GetBytes("ABCDEFGDSGFWEREW");
int bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.UTF8.GetString(data, 0, bytes);
如果 bytes < data.Length ,data 中就有垃圾数据了。
if (task.Wait(3000, token)) { return task.Result; } else { c.Cancel(); return "failed"; }
我这里有处理啊