我有几个关于完成 tcp 连接的问题。
客户端使用 Tcp 连接到我的服务器,在接受客户端后listener.BeginAcceptTcpClient(ConnectionEstabilishedCallback, null);
,我开始阅读networkStream.BeginRead(....)
.
当我等待消息时客户端断开连接会发生什么? (例如断电、断网等)
我怎么知道它什么时候发生?
如果成功读取后,我做了一些事情,然后调用networkStream.Close(); client.Close();
客户会看到什么?如何“优雅地”终止连接?
如果我正在等待读取(使用 BeginRead),然后(在不同的线程上)关闭同一个流,会发生什么情况?
编辑添加:我确实在客户端和服务器之间发生了乒乓消息。够了吗?如果我没有收到 ping,请终止我的 NetworkStream?肯定有更好的东西。
1-如果客户端由于电缆拔出而断开连接,您将不知道直到下一次读取或写入套接字。另请注意,tcpClient.Connected 属性值不可靠,它的值取决于上次通信;因此,如果最后一次通信成功,则其值为 true,否则为 false。有关该支票的更多信息this http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx.
2- 如果您关闭网络流和客户端,则客户端会正常终止。
3、我不知道,你测试一下吧。
如果您意识到由于电缆拔出等原因导致连接丢失,那么要获得适当的 IsConnected 值,您必须意识到在读取或写入 tcp 期间连接丢失,因此您需要通过盆栽尝试来访问 tcpclient 成员-捕获其操作......
使用此 IsConnected 属性检查 tcpClient 是否已连接:
public static bool IsConnected
{
get
{
try
{
//return _tcpClient != null && _tcpClient.Client != null && _tcpClient.Client.Connected;
if (_tcpClient != null && _tcpClient.Client != null && _tcpClient.Client.Connected)
{
/* As the documentation:
* When passing SelectMode.SelectRead as a parameter to the Poll method it will return
* -either- true if Socket.Listen(Int32) has been called and a connection is pending;
* -or- true if data is available for reading;
* -or- true if the connection has been closed, reset, or terminated;
* otherwise, returns false
*/
// Detect if client disconnected
if (_tcpClient.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (_tcpClient.Client.Receive(buff, SocketFlags.Peek) == 0)
{
// Client disconnected
return false;
}
else
{
return true;
}
}
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)