Maxim Gershkovich
Maxim Gershkovich

Reputation: 47199

TcpListener intermittently not working

Attempting to write a basic proxy I have implemented code along the following lines as a start.

private Thread _proxyThread;

public void Start() 
{
    this._proxyThread = new Thread(StartListener);
    this._proxyThread.Start();
}

protected void StartListener(object data)
{
    this._listener = new TcpListener(IPAddress.Any, 1234);
    this._listener.Start();

    while (true)
    {
        TcpClient client = this._listener.AcceptTcpClient();

        while (client.Connected)
        {
            NetworkStream stream = client.GetStream();

            StringBuilder request = new StringBuilder();

            byte[] bytes = new byte[1024];

            while (stream.DataAvailable && stream.CanRead)
            {   
                int i = stream.Read(bytes, 0, bytes.Length);
                request.Append(System.Text.Encoding.ASCII.GetString(bytes, 0, i));                        
            }

            if (stream.CanWrite)
            {
                byte[] response = System.Text.Encoding.Default.GetBytes("HTTP/1.1 200 OK" + Environment.NewLine + "Content-length: 4\r\n\r\n" + "Test");
                stream.Write(response, 0, response.Length);
            }

            client.Close();
        }
    }
}

I then set my LAN proxy like this

Proxy

My current goal (as you can hopefully deduce from my code) is to return just a text value with no headers or anything.

The problem that I am running into is that any of my attempts to run the code as is results in an intermittent behaviour where Chrome and IE9 will usually just return a ERR_CONNECTION_ABORTED or Internet Explorer cannot display the webpage respectively and very occasionally display the expected output "TEST".

I originally tried using a asynchronous approach (Using BeginAcceptTcpClient()) but have reverted back to this simpler technique because I thought this problem might stem from me doing something incorrectly in the asynchronous implementation but it seems that the cause is something else.

Could anyone please provide any guidance?

Upvotes: 0

Views: 548

Answers (2)

CodeCaster
CodeCaster

Reputation: 151720

It's not whether it's synchronous or asynchronous, you're just not responding with a proper HTTP response. Take a tool like Fiddler and look at the data being received when you request a regular webpage.

If you return this, it should work:

HTTP/1.1 200 OK
Content-length: 4

TEST

Upvotes: 1

usr
usr

Reputation: 171246

After your first iteration of the loop while (client.Connected) you close the connection. Only close it when you are done transferring all data.

Upvotes: 1

Related Questions