http://social.msdn.microsoft.com/Forums/windowsazure/en-US/203e904d-b581-4e53-81b6-86a4b71cf5f5/keeping-tcpclient-client-connected?forum=netfxnetcomI've read that document before. And implemented the line: Code Code Snippet StreamWrite("", NWStream2); Where the "" is a string to be sent. However this did not make a diffrence. I actually had to send something. I changed it toCode Snippet StreamWrite("0", NWStream2);This not only keeps the socket alive, it also throws the exception I was looking for.
这些方法都不是很可靠。如果你使用Intel的服务器网卡,它有硬件的诊断功能,用法在Intel开发者网站有。别的网卡就不行了。
参考这个博客来实现:http://www.cnblogs.com/zhili/archive/2012/08/25/TCP.html
{
get
{
if (tcpc == null)
return false;
// 另外说明:tcpc.Connected同tcpc.Client.Connected;
// tcpc.Client.Connected只能表示Socket上次操作(send,recieve,connect等)时是否能正确连接到资源,
// 不能用来表示Socket的实时连接状态。
try
{
if ((tcpc.Client.Poll(20, SelectMode.SelectRead)) && (tcpc.Client.Available == 0))
return false;
}
//catch (SocketException e)
//{
// if (e.NativeErrorCode != 10035)
// return false;
//}
catch
{
return false;
}
return true;
}
}
NetworkStream netstream = tcpClient.GetStream();
StreamReader reader = new StreamReader(netstream);
string temp = "";
temp = reader.ReadLine();
if (temp == null)
{
MessageBox.Show("连接断开");
}
else
{
MessageBox.Show(temp);
}
不管是客户端,人为的关闭连接 ,或者客户端,直接关闭程序,都会弹出连接断开
FORMCLOSEING事件 不要加TCPCLIENT.CLOSE();可以测试
{
while (true)
{
tcpclient = new TcpClient();
int count = 0;
while (tcpclient.Connected == false)
{
try
{
tcpclient.Connect(IPAddress.Loopback, 8888);
if (tcpclient.Connected)
break;
}
catch (Exception ex)
{
}
}
}
WriteStream = tcpclient.GetStream();
ReadStream = tcpclient.GetStream();
recv_Message();
while (tcpclient.Connected)
{
}
}
}
此函数的功能是当服务器关闭程序后,客户端能自动连接重启后的服务器。但是当把recv_Message()函数去掉后,tcpclient.Connected总是为true,请问是什么原因?
http://hi.baidu.com/gaoxiaotiger/item/d337d2245a3468cea5275ac0
Code
Code Snippet
StreamWrite("", NWStream2); Where the "" is a string to be sent. However this did not make a diffrence. I actually had to send something. I changed it toCode Snippet
StreamWrite("0", NWStream2);This not only keeps the socket alive, it also throws the exception I was looking for.