Vb.net 无法使端口关闭
我正在尝试修复一个使用TCP接收文件的应用程序。不幸的是,我没有发送应用程序的源代码。我遇到的问题是,在接收到第一个文件后,第二个文件由发送应用程序发送,但接收应用程序没有接收到它 我认为问题在于,套接字在收到文件后没有关闭。我有一个应该关闭它的方法,但是_socket.Connected=false,所以什么也没做。但是,如果我检查端口,即使在套接字关闭之后,它仍然被绑定Vb.net 无法使端口关闭,vb.net,sockets,tcp,Vb.net,Sockets,Tcp,我正在尝试修复一个使用TCP接收文件的应用程序。不幸的是,我没有发送应用程序的源代码。我遇到的问题是,在接收到第一个文件后,第二个文件由发送应用程序发送,但接收应用程序没有接收到它 我认为问题在于,套接字在收到文件后没有关闭。我有一个应该关闭它的方法,但是_socket.Connected=false,所以什么也没做。但是,如果我检查端口,即使在套接字关闭之后,它仍然被绑定 Private Sub CloseSocket(ByVal disconnect As Boolean)
Private Sub CloseSocket(ByVal disconnect As Boolean)
If Not (_socket Is Nothing) Then
If (_socket.Connected = True) Then
_socket.Shutdown(SocketShutdown.Both)
If(disconnect) Then
_socket.Disconnect(True)
End If
End If
_socket.Close()
_socket = Nothing
End If
End Sub
我意识到我没有包含太多的代码,但是Listen方法非常大而且复杂。我可以得到额外的代码,如果它将提供洞察力。如蒙协助,将不胜感激
编辑
用于检查端口状态的代码如下:
Private Shared Function TcpIpGetPortStatus(ByVal port As Int32) As String
Dim properties As NetworkInformation.IPGlobalProperties
Dim listeners As Net.IPEndPoint()
Dim local As Net.IPEndPoint
Dim connections As NetworkInformation.TcpConnectionInformation()
Dim t As NetworkInformation.TcpConnectionInformation
Dim portStatus As String
portStatus = "Disconnected"
properties = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
listeners = properties.GetActiveTcpListeners()
Try
' Cycle through all listening TCP connections and find the one that is associated with port.
For Each local In listeners
If (local.Port = port) Then
portStatus = "Connected"
Exit For
End If
Next local
' Port wasn't in the listening state so check if it is established.
If (portStatus = "Disconnected") Then
properties = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
connections = properties.GetActiveTcpConnections()
' Cycle through all active TCP connections and find the one that is associated with port.
For Each t In connections
If (t.LocalEndPoint.Port = port) Then
Select Case t.State
Case NetworkInformation.TcpState.Established
portStatus = "Connected"
Exit For
End Select
End If
Next t
End If
Catch ex As Exception
' Handle Exception...
End Try
Return portStatus
End Function
调用此函数时,将返回“已连接”。我追踪了一下,发现我使用的端口仍然是绑定的。再次感谢您的帮助
加成
我只是在两个独立的系统之间运行,使用WireShark捕获数据。有一个发送方和接收方,我没有源代码,正在尝试与之集成,还有一个发送方和接收方,我正在更新代码以使其与现有的发送方和接收方正确通信。在这两种情况下发送的流是相同的(除了ACK中的datetime)。如果我从现有发送方向正在升级的接收方发送第二条消息,消息将被发送到端口,但开发中的接收方从未收到通知,这会挂起两个程序。在对提供给我的代码进行反复检查后,我终于意识到它关闭并断开了错误的套接字。它不是在用于接收消息的套接字上调用Shutdown和Disconnect,而是在侦听套接字上调用 一旦我意识到这一点,我就能够关闭正确的套接字,应用程序开始工作。现在,我只需要检查并纠正底层代码中的所有问题,事情应该会好起来
感谢所有回应的人。你让我朝着正确的方向思考。可能问题是,在收到文件后,套接字关闭了,你应该让它在同一个连接上打开,以打开另一个文件?为什么不干脆取消对
已连接的
的检查,然后调用关机()
和断开()
无条件?@Remy我确实尝试过,但引发了套接字异常。它说插座未连接,但当我检查打开的插座列表时,我发现它已连接。我添加了用于检查打开连接的代码。实际上,他只需要无条件地调用_socket.Close()和_socket.Dispose()。(将其放入try/catch块以捕获任何异常)。跳过断开和关机呼叫。这可能是关闭插座的最佳方式。但我怀疑EJP的建议是正确的。插座根本不应该关闭。@selbie谢谢您的回复。我确实调用了_socket.Close,它似乎应该释放套接字,但它仍然保持打开状态。不过,我正在研究是否有可能让连接保持打开状态。我已经删除了对CloseSocket的所有调用,但仍会遇到无法接收下一个文件的问题。我想我应该开始研究是否需要做一些事情,以便在收到文件后再次启动应用程序侦听。