2017-07-26 175 views
-1

我在使用tcp客戶端時遇到問題。當客戶端開始他們的表單時,他們向我發送一個client.connect請求,當我打開我的表單時,我接受傳入的請求,因此我們都連接並顯示連接,但是當我關閉客戶端表單時它仍然顯示我們即使我們不是。TCP/IP客戶端連接問題

Dim Listener As New TcpListener(4355) 
    Dim Client As New TcpClient 
    Dim Message As String 

    Private Sub Listen() 
    Try 
     Listener.Start() 


    Catch ex As Exception 

    End Try 
    End Sub 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles 
    MyBase.Load 
    Control.CheckForIllegalCrossThreadCalls = False 
    'IP.Text = My.Settings.IP 
    Try 
     Dim Listening As New Thread(New ThreadStart(AddressOf Listen)) 
     Listening.Start() 


    Catch ex As Exception 
     Application.Restart() 
    End Try 
    Sending1.Focus() 
    End Sub 

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles 
    Timer2.Tick 
    If Client.Connected = False Then 
     Label5.Text = "Disconnected" 
     Label5.ForeColor = Color.Red 
     Sending1.Enabled = False 
     Client = Listener.AcceptTcpClient() 'looping accept request 
    End If 
    If Client.Connected = True Then 
     Label5.Text = "Connected" 
     Label5.ForeColor = Color.Green 
     Sending1.Enabled = True 
    End If 
    End Sub 
+0

太少代碼爲我們能夠重現,或發現任何問題。開始:此代碼位於何處?在一個按鈕?計時器?線?其他?請更新您的問題,以包含我們重現問題所需的最低代碼。有關指導,請參閱[如何創建最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)。 –

+0

已更新,對此表示抱歉 – alan7811

+1

我看到您仍在使用Control.CheckForIllegalCrossThreadCalls = False。您_ **迫切** _需要擺脫這一點,並做[**適當的線程安全調用**](https://stackoverflow.com/documentation/vb.net/1913/threading/6235/performing-而是使用線程安全調用使用控制調用)。我不是這樣說的,因爲這是做這件事的最好方式,我這樣說是因爲_ **你必須!** _ –

回答

0

您可以使用ElseIf

If Client.Connected = False Then 
    Label5.Text = "Disconnected" 
    Label5.ForeColor = Color.Red 
    Sending1.Enabled = False 
    Client = Listener.AcceptTcpClient() 

ElseIf Client.Connected = True Then 
    Label5.Text = "Connected" 
    Label5.ForeColor = Color.Green 
    Sending1.Enabled = True 
End If 

希望它能幫助:)

+0

它沒有區別。 OP沒有給我們足夠的代碼來識別問題。 –

+0

已更新,對此感到遺憾。 – alan7811