Rahul
Rahul

Reputation: 75

Close the Socket Listener application after 30 seconds if there is no response

(C#) Here I created a socket listener application which waits for the client hit. Now my requirement is my application should listen up to 30 seconds only later it should throw an error saying "Request Timed Out". Any suggestions ?

        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);
        }

Upvotes: 0

Views: 2081

Answers (2)

Maxim
Maxim

Reputation: 7348

Why would you want to limit the time that the server listening ?

Server should be listening all the time that it's running.

Anyway, You can create a task(thread) that will be listening and after the timeout will be canceled.

Upvotes: 0

Jeff LaFay
Jeff LaFay

Reputation: 13350

I would think that the ReceiveTimeout property being set to 30 seconds would take care of that for you. Have you tried that yet?

client.ReceiveTimeout = 30000;

The property defaults to 0, so you would want to set that. It throws an IOException. You could catch that and throw the exception of your choosing to bubble up the application.

Upvotes: 2

Related Questions