TcpListener不会失去联系

时间:2014-07-12 11:58:55

标签: .net vb.net

我是Visual Basic和.NET的菜鸟,所以请原谅我可能简单而愚蠢的问题。 我想创建一个简单的服务器客户端连接。这现在有效,我的客户端可以连接到服务器。但是,如果我关闭客户端,服务器仍然认为客户端已连接。这是我的代码:

Private server As TcpListener
Private serverPort As Integer = 8000
Private connectionMonitor As Tasks.Task
Private clientList As New List(Of Connection)

Public Structure Connection
    Dim client As TcpClient
End Structure

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    StartServer()
End Sub

Private Sub StartServer()
    server = New TcpListener(IPAddress.Any, serverPort)
    server.Start()
    server.BeginAcceptTcpClient(AddressOf DoAcceptClient, server)
    Console.WriteLine("Server started")
    connectionMonitor = Tasks.Task.Factory.StartNew(AddressOf DoMonitorConnections)
End Sub

Private Sub DoAcceptClient(result As IAsyncResult)
    ' Get the listener that handles the client request.
    Dim listener As TcpListener = CType(result.AsyncState, TcpListener)

    Dim client As TcpClient = listener.EndAcceptTcpClient(result)

    ' Process the connection here.
    Console.WriteLine("Client connected")
    Dim c As Connection = New Connection
    c.client = client
    clientList.Add(c)
End Sub

Private Sub DoMonitorConnections()
    Dim a As Integer = 0
    While True
        For index As Integer = 0 To clientList.Count - 1 Step 1
            Dim conn As Connection = clientList(index)
            If conn.client.Connected Then
                Console.WriteLine("Client still conncected" & a)
                Console.WriteLine(conn.client.Connected)
            Else
                Console.WriteLine("Client connection lost")
                clientList.Remove(conn)
            End If
            a += 1
        Next
        ' throttle loop
        connectionMonitor.Wait(1000)
    End While
End Sub

DoMonitorConnections()我检查,如果客户端仍然连接。虽然客户端应用程序已关闭,但我仍然得到输出"仍然连接",因为TcpClient的连接属性始终为True。

3 个答案:

答案 0 :(得分:0)

尝试向客户发送内容并抓住错误......:

Private Sub DoMonitorConnections()
         While ...
            For index ...
            .
            .
                Try
                    Dim tmp(0) As Byte
                    conn.client.Client.Send(tmp)
                    Console.WriteLine("---Connected!---")
                Catch e As SocketException
                    Console.WriteLine("--Disconnected: error code {0}!", e.NativeErrorCode)
                End Try
            .
            .
        .
End Sub

答案 1 :(得分:0)

要手动发送/接收套接字,您必须设计一个实体模式,以便双方知道何时应完成事务。完成连接后,双方必须呼叫关机,然后呼叫断开连接。

使用套接字后,请务必查看WCF,因为它使一切变得更加简单和清洁。

答案 2 :(得分:0)

套接字仅代表连接的一端。如果没有正常关闭连接(Socket.Shutdown,等待0个字节,然后调用socket.Close()),则在另一端检测到断开连接之前可能需要一些时间。

断开连接的明确指示是SendReceive报告已传输0个字节。这是检查连接是否仍处于活动状态的最佳方法。