Emre Kantar
Emre Kantar

Reputation: 106

Socket read and write in a loop

I want to read and write to a socket in a infinite loop.

When i write a request to stream in first loop, i can read the response immediately.

But for the other loops networkStream.DataAvailable is always false.

How can i read and write continuously to the socket.

    static void ReadWriteSocket()
    {
        string requestString = "GET /WebApplication.UI HTTP/1.1 \r\n" +
                               "Host: 172.17.107.30 \r\n" +
                               "Connection:close \r\n\r\n";

        client = new TcpClient();
        client.Connect(new IPEndPoint(IPAddress.Parse("172.17.107.30"), 80));

        byte[] buffer = System.Text.Encoding.Default.GetBytes(requestString);
        byte[] readBuffer = new byte[1024];

        using (MemoryStream ms = new MemoryStream())
        {
            while (true)
            {
                var networkStream = client.GetStream();

                networkStream.Write(buffer, 0, buffer.Length);

                networkStream.Flush();

                int recievedByte = 0;

                if (networkStream.DataAvailable)
                {
                    while ((recievedByte = networkStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    {
                        ms.Write(readBuffer, 0, recievedByte);
                    }
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(ms.ToArray()));
            }
        }
    }

Upvotes: 0

Views: 998

Answers (1)

Emre Kantar
Emre Kantar

Reputation: 106

Finally i found the leak.

The tcp connection is closed by the http header Connection:close

So server does not respond to my new request.

I changed the respective header to Connection:keep-alive

thanks.

Upvotes: 1

Related Questions