我一直在争取整个3天的一个问题我找不到任何解决方案,请帮助:)
我使用Visual Studio 2010和C#语言。如何在连接后测试TCPClient断开的连接?
我有一个像服务器一样工作的设备,它在非常不规则的时间段内发送一些数据(不可能定义任何读取超时)。
我写了一个TCP客户端连接到该服务器并读取数据。它工作正常,但是当网络出现问题并且服务器变得不可用时(例如,当我从计算机中拔出网线时),应用程序需要大约10秒钟才能“注意到”,并且没有连接到服务器并抛出一个例外。 (我不知道为什么正好10秒?它在什么地方被定义了?我可以改变它吗?)
我想反应更快 - 比方说连接断开一秒后。
谷歌搜索答案然而不提供任何工作解决方案。
测试代码如下,我尝试在2个线程上进行测试:一个是读取数据,另一个是查找连接状态,当它断开时应该报警。它不适用于TCPClient和Socket类。我试图用tcpClient.SendTimeout = 100;
和stream.WriteTimeout = 100;
读取/写入一些数据,但它似乎不起作用。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace TCPClient
{
class Program
{
static volatile bool _continue = true;
static TcpClient tcpClient;
static NetworkStream stream;
static void Main(string[] args)
{
try
{
//client thread - listen from server
Thread tcpListenThread = new Thread(TcpListenThread);
tcpListenThread.Start();
//connection checking thread
Thread keepAliveThread = new Thread(KeepAliveThread);
keepAliveThread.Start();
while (_continue)
{
if (Console.ReadLine() == "q")
{
_continue = false;
}
}
keepAliveThread.Join(2000);
if (keepAliveThread.IsAlive)
{
Console.WriteLine("Thread keepAlive has been aborted...");
keepAliveThread.Abort();
}
tcpListenThread.Join(2000);
if (tcpListenThread.IsAlive)
{
Console.WriteLine("Listen thread has been aborted...");
tcpListenThread.Abort();
}
}
catch (Exception ex)
{
Console.WriteLine("\n" + ex.Message);
}
Console.WriteLine("\nHit any key to quit...");
Console.Read();
}
private static void TcpListenThread()
{
string server = "172.20.30.40";
int port = 3000;
try
{
using (tcpClient = new TcpClient())
{
tcpClient.Connect(server, port);
if (tcpClient.Connected)
Console.WriteLine("Successfully connected to server");
using (stream = tcpClient.GetStream())
{
while (_continue)
{
Byte[] data = new Byte[1024];
Int32 bytes = stream.Read(data, 0, data.Length);
string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}, responseData);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Listen thread exception! " + ex.Message);
}
}
private static void KeepAliveThread()
{
while (_continue)
{
if (tcpClient != null)
{
try
{
//...what to put here to check or throw exception when server is not available??...
}
catch (Exception ex)
{
Console.WriteLine("Disconnected...");
}
}
Thread.Sleep(1000); //test for connection every 1000ms
}
}
}
}
编辑:
@卡斯滕的回答是:虽然它看起来很有希望,这种解决方案不工作...
我做了最简单的测试应用程序:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace TCPClientTest
{
class Program
{
static void Main(string[] args)
{
try
{
string server = "172.20.30.40";
int port = 3000;
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.Connect(server, port);
int i = 0;
while (true)
{
// This is how you can determine whether a socket is still connected.
bool blockingState = tcpClient.Client.Blocking;
try
{
byte[] tmp = new byte[1];
tcpClient.Client.Blocking = false;
tcpClient.Client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
Console.WriteLine("Still Connected, but the Send would block");
else
{
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
tcpClient.Client.Blocking = blockingState;
}
Console.WriteLine("Connected: {0} ({1})", tcpClient.Client.Connected, i++);
Thread.Sleep(1000);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Global exception: {0}", ex.Message);
}
}
}
}
结果显示如下:
连接!
连接:真
加上我的订单号每隔一秒。当我断开网络电缆时,开始打印需要8秒钟:
Disonnected:error code 10054!
连接:假
so by 8 seconds我不知道连接丢失。看起来pinging是最好的选择,但我会测试另一种解决方案。
可能的重复:[如何检查(TCP)套接字是否(在C#中)(dis)连接?](http://stackoverflow.com/questions/515458/how-can-i-check-whether-a -tcp-socket-is-disconnected-in-c) – ladenedge
@ladenedge可能重复...除了这个有更多的示例代码来帮助其他人以不同的方式学习。我知道你的评论已经过时了,但是当你这样的人毫无用处并且不鼓励那些效率不高的评论时,这令人沮丧。 – Euthyphro