2010-12-19 39 views
0

我在服務器程序和客戶端程序之間使用TCP套接字連接。多個客戶端程序必須連接到同一個端口。問題是,如果我關閉客戶端程序,我得到的服務器程序出現以下錯誤:如何正確處理中斷的TCP連接?

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host 
    at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) 
    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult) 

http://i55.tinypic.com/nh135w.png

如果我處理這個由一個try/catch,我再不能再與客戶端程序-connect,因爲它提供了以下錯誤(在客戶端程序):

No connection could be made because the target machine actively refused it 127.0.0.1: 1234 

下面是在服務器程序監聽代碼。我希望能得到一些幫助明白我怎麼可以處理客戶端程序,關機/重啓&無需重新連接服務器程序失敗..

' This is the callback function for TcpClient.GetStream.Begin, It begins an asynchronous read from a stream. 
    Private Sub DoRead(ByVal aread As IAsyncResult) 
     Dim BytesRead As Integer 
     Dim strMessage As String 

     ' Try 
     ' Ensure that no other threads try to use the stream at the same time. 
     SyncLock _client.GetStream 
      ' Finish asynchronous read into readBuffer and get number of bytes read. 
      If Client.Connected Then 
       BytesRead = _client.GetStream.EndRead(aread) 
      End If 
     End SyncLock 

     ' Convert the byte array the message was saved into, minus one for the Chr(13) (carriage return). 
     strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 1) 
     ProcessIncoming(strMessage) 

     ' Ensure that no other threads try to use the stream at the same time. 

     SyncLock Client.GetStream 
      ' Start a new asynchronous read into readBuffer. 
      Client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing) 
     End SyncLock 
     'Catch e As Exception 
     ' ' This triggers if userlist is found empty 
     ' ' Then gives problem, as it cant close the connection or something.. ?? 
     ' Debug.Print("UserConnection.DoRead Exception: " & e.ToString) 
     ' CloseConnetion("Error: Stream Reciever Exception") 

     'End Try 

    End Sub 

回答

1

你不知道。你是服務器。您關閉了插座並忘記了它。如果客戶想要更多服務,則由他來重新連接。

+0

謝謝!你的意思是,這個錯誤然後由try/catch來處理,並且我不應該改進這個邏輯?然而,在這種情況下,仍然必須有我丟失的東西,因爲我無法連接,當我重新啓動客戶端..因爲它說「目標機器積極拒絕...」 – bretddog 2010-12-20 09:47:14

+0

嗯。不知道我改變了什麼,但似乎現在工作。 – bretddog 2010-12-20 12:22:32

相關問題