2010-12-19 116 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

相关问题