2015-08-24 119 views
1

我有一個線程和套接字服務器來監聽客戶端。客戶端軟件不適合我,它是一個將數據發送到我的程序的實驗室軟件。客戶端無法連接到我的套接字服務器 - VB.NET

當開始收聽時沒有問題,但是當客戶端軟件關閉並重新打開時,無法將任何數據發送到我的軟件。

我的監聽器必須每次都像服務一樣運行。

這是我的代碼:

Delegate Sub WriteMsgHandle(ByVal Msg As String) 
Dim handler As WriteMsgHandle 

Dim THS As ThreadStart 
Dim TH As Thread 
Private Sub btnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListen.Click 
    Try 
     btnListen.Enabled = False 

     THS = New ThreadStart(AddressOf Listen) 
     TH = New Thread(THS) 
     TH.Start() 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 

End Sub 
Public Sub Listen() 
    Dim bytesReceived As Integer = 0 
    Dim recv() As Byte = New Byte(1) {} 
    Dim clientSocket As Socket 
    Dim listenerSocket As New Socket _ 
     (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) 
    Dim IPHost As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName()) 
    Dim localadd As IPAddress = IPAddress.Parse(txt_ip.Text) 
    Dim ipepServer As IPEndPoint = New IPEndPoint(localadd, txt_port.Text) 
    handler = AddressOf WriteMsg 
    listenerSocket.Bind(ipepServer) 
    listenerSocket.Listen(-1) 
    clientSocket = listenerSocket.Accept() 

    Dim msgcount As Integer = 0 

    If clientSocket.Connected Then 

     MsgBox("Connected") 

     Do 
      bytesReceived = clientSocket.Receive(recv) 
      Dim Msg As String 

      Msg = Encoding.ASCII.GetString(recv) 
      Invoke(handler, Msg) 

     Loop While bytesReceived <> 0 

    End If 
End Sub 

回答

0
  1. 你只接受一次。你需要循環接受。
  2. If clientSocket.Connected Then你爲什麼加這個?刪除該支票。插座剛被接受,因此它已連接。即使它斷開連接,你是否想忽略那個錯誤狀態?!
  3. 接收環路是正確的。
  4. 您可能想要在新線程上啓動每個接受的客戶端(或使用異步IO)。
+0

謝謝,但我需要知道什麼時候從客戶端收到的數據結束髮送一個字符串。我怎麼知道? –

相關問題