关于TcpListener无限循环监听的问题
我首先启用一个新线程,然后用do while true 无限循环调用AcceptTcpClient()进行阻塞监听,但关闭的时候总是报错,究竟应该再怎么正常关闭呢?
关闭时我重写Finalize()函数
If Not listener Is Nothing Then
listener.Stop() '关闭监听
listener = Nothing '释放资源
End If
If Not thread Is Nothing Then
thread.Join() '等待线程完成工作
thread = Nothing '释放资源
End If
MyBase.Finalize()
还有就是在thread.Join()的时候,那个线程总是完成不了工作,也许是因为这个线程是个无限循环,可是我应该怎么判断我已经关闭了Listener来终止循环呢
以下是循环的全部内容
Do While True '循环等待入站连接
Dim _client As TcpClient = listener.AcceptTcpClient() '接收挂起的连接请求
If _client Is Nothing Then '如果没有入站连接,则跳出循环
Exit Do
End If
builder = New StringBuilder
With builder
.Append(Environment.NewLine)
.Append(Environment.NewLine)
.Append( "客户端 ")
.Append(pub.ClientIP(_client))
.Append( " 请求连接! 时间: ")
.Append(DateTime.Now.ToString())
.Append(Environment.NewLine)
End With
main.LastConnetionTime(pub.ClientIP(_client), DateTime.Now.ToString())
main.ShowResult(builder.ToString())
If Not AnalyseTcpClent(_client) Then
Dim _netStream As NetworkStream = _client.GetStream()
_netStream.Close()
_client.Close()
_client = Nothing
Else
builder = New StringBuilder
With builder
.Append( "合法地址允许连接! 时间: ")
.Append(DateTime.Now.ToString())
.Append(Environment.NewLine)
.Append( "接收内容: ")
End With
main.ShowResult(builder.ToString())
main.ReceiveInboundConnection(_client) '将处理的连接传递给主窗体
End If
Loop
[解决办法]
thread.Abort()
thread = null;
就强行退出了