2012-11-07 30 views
1

我在客戶端TCP/IP應用程序中使用Socket類將我的客戶端連接到服務器。使用套接字連接到相同的端點

我有以下代碼:

var endPoint = new IPEndPoint(IPAddress.Parse(IP), port); 
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
         ProtocolType.Tcp); 

client.Connect(endPoint); 

try 
{ 
    while (true) 
    { 
     // Do work... 
     // Receive/Send data from/to server 
    } 
} 
catch (SocketException) 
{ 
    /* At some point the server disconnects... 
    Exception catched because the server close the connection 
    Socket error 10054 - WSAECONNRESET */ 

    // So I try to reconnect 
    if(client.Connected == false) 
    { 
     /* The following line throws a InvalidOperationException. 
     Message: After disconnecting the socket, you can reconnect only 
     asynchronously from a different EndPoint. BeginConnect must be 
     called on a thread that will not close until the operation completes.*/ 
     client.Connect(endPoint); 

     /* So I try instead Socket.BeginConnect, but the following line 
     throws a SocketException 10061 - WSAECONNREFUSED */ 
     client.BeginConnect(endPoint, ConnectCallback, client); 

     /* And also the following code throws a 
      SocketException 10061 - WSAECONNREFUSED */ 
     client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
           ProtocolType.Tcp); 
     client.Connect(endPoint); 
    } 
} 

Here套接字錯誤的列表。

所以,在某些時候,服務器關閉連接,我需要知道什麼是知道什麼時候該服務器已準備好接受另一個連接,以及如何再次連接到同一個終點的最好方法。

回答

1

WSAECONNREFUSED表示服務器不接受您的連接請求。

您必須重試連接,並在重試之間休眠幾秒鐘。客戶端無法知道服務器何時再次可用,而無需連接。

+0

我在想同樣的解決方案,但[我不想使用Thread.Sleeep](http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-一個點登錄的-A-設計拙劣的-program.aspx)。 – Nick

+1

你可以做任何你想做的事情,但你絕對不應該在緊密的循環中調用'client.Connect()'。在後臺線程中進行連接時,使用'Thread.Sleep'就沒有什麼可說的了。 – Jan

+0

但我有沒有創建一個新的套接字? – Nick

相關問題