110,535
社区成员
发帖
与我相关
我的任务
分享
s.Listen(100);
while (true)
{
byte[] bytes = new byte[1025];
Socket ss = s.Accept();
try
{
ss.ReceiveTimeout = 0;
while (true)
{
ss.Receive(bytes);
//这里我如何检测对方的连接已经断开?本来指望对方断开后这里会出现异常自动退出循环的,问题是对方断开后,依然可以接收到数据,并不发生异常
string rmsg = Encoding.Default.GetString(bytes);
rmsg = rmsg.Substring(0, rmsg.IndexOf('\0'));
textBox1.Text = textBox1.Text + rmsg;
if (rmsg == "close") break;
//当连接方没有发送close直接断开后,这里会进入死循环,并且持续得到连接方最后发来的一笔数据
}
ss = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ss.Close();
}
}
检查tcpclient的active属性
举例说明
[C#]
// This derived class demonstrates the use of three protected methods belonging to the TcpClient class
public class MyTcpClientDerivedClass : TcpClient
{
// Constructor for the derived class.
public MyTcpClientDerivedClass() : base()
{
}
public void UsingProtectedMethods()
{
// Uses the protected 'Active' property belonging to the TcpClient base class
// to determine if a connection is established.
if (this.Active){
// Calls the protected 'Client' property belonging to the TcpClient base class.
Socket s = this.Client;
// Uses the Socket returned by Client to set an option that is not available using TcpClient.
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
// To free all resources, calls the protected virtual method Dispose belonging to the TcpClient base class.
this.Dispose(true);
GC.SuppressFinalize(this);
}
}