2011-02-28 39 views
0

(C#)在這裏我創建了一個等待客戶端命中的套接字偵聽器應用程序。現在我的要求是,我的應用程序應該只聽到30秒後應該拋出一個錯誤,說「請求超時」。有什麼建議麼 ?如果沒有響應,在30秒後關閉套接字偵聽器應用程序

 try 
     { 
      Byte[] bytes = new Byte[256]; 
      String data = null; 
      // Enter the listening loop. 
      while (true) 
      { 
       ReceiveTimer.Stop(); ; 
       logger.Log("Waiting for a connection... "); 

       // Perform a blocking call to accept requests. 
       // You could also use server.AcceptSocket() here. 
       TcpClient client = server.AcceptTcpClient(); 


       logger.Log("Connected!"); 

       data = null; 

       // Get a stream object for reading and writing 
       NetworkStream stream = client.GetStream(); 

       int i; 

       // Loop to receive all the data sent by the client. 
       while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) 
       { 
        // Translate data bytes to a ASCII string. 
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 
        logger.Log("Received: {0}", data); 

        // Process the data sent by the client. 
        data = data.ToUpper(); 

        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); 

        // Send back a response. 
        stream.Write(msg, 0, msg.Length); 
        logger.Log("Sent: {0}", data); 
       } 

       // Shutdown and end connection 
       client.Close(); 
       logger.Log("Shutdown and end connection"); 
      } 
     } 
     catch (SocketException ex) 
     { 
      logger.Log("SocketException: " + ex); 
     } 

回答

0

爲什麼要限制服務器偵聽的時間?

服務器應該一直在監聽它的運行。

無論如何,您可以創建一個將要監聽的任務(線程),超時後將被取消。

+0

由於安全問題 – Rahul 2011-02-28 14:15:06

2

我會認爲將ReceiveTimeout屬性設置爲30秒會照顧到你。你試過了嗎?

client.ReceiveTimeout = 30000; 

該屬性默認爲0,因此您需要設置它。它拋出一個IOException。你可以捕捉並拋出你選擇的例外來冒充應用程序。

+0

我希望client.ReceiveTimeout屬性將在任何客戶端點擊偵聽器後超時,但我的要求是停止偵聽器而不考慮客戶端請求。 – Rahul 2011-02-28 14:40:27