I have a static method

```
public class TelnetClient
{
    public static string SendAndReceiveData2(string data, string HostIPAddress, int Port)
    {
        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            socket.Connect(HostIPAddress, Port);
            byte[] bytesToSend = Encoding.ASCII.GetBytes(data);
            socket.ReceiveTimeout = 3000;
            socket.SendTimeout = 3000;
            int bytesSent = socket.Send(bytesToSend);
            if (bytesSent != bytesToSend.Length)
            {
                throw new Exception("Invalid send byte number");
            }

            byte[] bytesReceiveBuffer = new byte[1024];
            int bytesRec = socket.Receive(bytesReceiveBuffer); //No need to loop for testing
            string returnedData = Encoding.ASCII.GetString(bytesReceiveBuffer, 0, bytesRec);

            socket.Close(); // Just out of desperation
            socket.Dispose();
            return returnedData;
        }
    }
 }

```

and this is how I am calling it:

```
for (int i = 0; i < 10; i++)
{
    TelnetClient.SendAndReceiveData2("some data different each time", "127.0.0.1", 1234);
}

```

I am calling this method in a loop. This methods sends some commands to a third party application which returns a response immediately. The issue is that this code works for the first iteration but on the second iteration, it fails at `socket.Receive` with error:

> 
> A connection attempt failed because the connected party did not
>  properly respond after a period of time, or the established connection
>  failed because the connected host has failed to respond.
> 
> 
> 

Here is the tricky part, If instead of looping multiple times, I close the `exe` and start again through command prompt, I don't get the error and also the third party app receives multiple requests as well. 

This led me to believe that **somehow the socket is not getting disposed properly in the loop. But if I close the process and start again, it has no problem.** 

I have checked that the `socket.LocalEndPoint` points to different port each time. Also `socket.Available` is set to `0` on second iteration. 

I am not really sure what is going on, and would appreciate any help.