simple proxy server

csharp Netherlands
  • 13 years ago

    Hello Developer Fusion community,

    I will try to explain my problem eventhough is not easy to explain. Im new to C# and Im trying to build a proxy server (browser <--> proxy <--> http server). What i've programmed so far is working but it is very unstable.  And here is where i'm counting on some help. Why does it stop working properly after time? I get exceptions like:

    IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.

    U can check the code below to see how my code looks like. It consist of 2 classes. but im only posting the one with relevance to us Because I've been testing so much the code doesn't have any comments. It's a multithreaded applications. I use a tcplistener,  tcpclient, networkstream and thread. Further I use dictionary too ( which basically is not really relevant to the problem). I use tcplistener to listen for clients and then each client is set to a different thread so that its request can be processed. So what I do is I simply take the request and make another tcpClient and sent this request to the real server and wait for the http response. Everything is being logged on a listbox so that i can see the progress is doing. This process goes well with simple websites. But I've checked the packets (with a packet analyzer) and there was nothing wrong with the way data comes in and out of the application. I use internet explorer 6.0 as the testing browser.

    Things that are bothering me are sometimes:

    **

    i want to close the connection (networkstream.close (); tcpclient.close();) after the client is done and there are no more data on the stream and I get an error that tcpclient was dispose so it cannot read from it. But ofcourse not It was done. So I'm not sure why its doing this. I expect it to make a new connection and ofcourse a new tcpclient is created.

    I type an URL sometimes in the adress bar and press enter and nothing happens in my application and i wait like 30 seconds and then I see all of sudden the logfile that i just received a request. And it makes me wonder...

    Sometimes when everything goes well (meaning all the data needed to generate the page with everything has passed)... the IE6 progressbar is showing that is not done and it keeps that state. So should the proxy send something extra to tell him its done?

    When I close the proxy (with windows red close button) it GUI disappears but I still have to stop it manually in VS.NET 2005. This happens from time to time and I'm not sure why.

    **

    I think I need to know how to debug better with vs.NET 2005. Im only using breakpoints to walk through the code. What else can use in VS to debug better? Any more info just let me know and I will provide u with them.

     







    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.IO;










    namespace SimpleProxy
    {
        public partial class Form1 : Form
        {
            TcpClient tcProxy;
            TcpClient tcClient;
            NetworkStream nsProxy;
            NetworkStream nsClient;
            TcpListener tlProxy;
            Thread thProxyServer;
            Thread listenerthread;
            String strRequest, Hostnaam;
            string strResponse = "";
            
           














            delegate void SetTextCallback(string text);
            public Form1()
            {
                InitializeComponent();
            }



            private void Form1_Load(object sender, EventArgs e)
            {
                tlProxy = new TcpListener(IPAddress.Any, 4280);
                tlProxy.Start();
                listenerthread = new Thread(new ThreadStart(StartServer));
                listenerthread.Start();
                SetText("listening for a client...");






            }
            private void StartServer()
            {
                    while (!tlProxy.Pending())
                    {
                        tcProxy = tlProxy.AcceptTcpClient();




                        SetText("A client '" + "'  is connecting...");
                        thProxyServer = new Thread(new ThreadStart(ReceiveData));
                        thProxyServer.Start();
                    }
                }       




            private void ReceiveData()
            {
                int recv = 0;
                String strMessage;
                Byte[] data = new Byte[1024];
                nsProxy = tcProxy.GetStream();
                strMessage = "connected!";
                SetText(strMessage);
                strMessage = "";
                while (true)
                {
                    Codec dict = new Codec();
                    try
                    {
                       
                            recv = nsProxy.Read(data, 0, data.Length);















                        if (recv ==0)
                        break;

                        strRequest = Encoding.ASCII.GetString(data, 0, recv);
                      
                        char[] delimit = new char[] { '\r', '\n' };
                        foreach (String sbReqs in strRequest.Split(delimit, StringSplitOptions.RemoveEmptyEntries))
                        {
                             SetText(sbReqs.ToString());
                        }
                       
                        dict.sorteer(strRequest);
                        Hostnaam = dict.Hostnaam();
                        SendRequest(strRequest);
                        nsProxy.Flush();
                       
                    }
                    catch (IOException e)
                    {
                        SetText("connection closed\n");
                        SetText("Reason:" + e.ToString());
                        break;
                    }
                  
                }
                //nsProxy.Close();
                //tcProxy.Close();
                SetText("connection closed Proxy");
























            }
            public void SetText(string text)
            {
                if (this.lstLogProxy.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(SetText);
                    this.Invoke(d, new object[] { text });
                }
                else
                {
                    this.lstLogProxy.Items.Add(text);
                }
            }











            private void btnClear_Click(object sender, EventArgs e)
            {
                lstLogProxy.Items.Clear();
            }



            private void SendRequest(string text)
            {
                int recv = 0;
                tcClient = new TcpClient(Hostnaam, 80);
                nsClient = tcClient.GetStream();
                Byte[] data = new Byte[1024];
                data = Encoding.ASCII.GetBytes(strRequest);
                nsClient.Write(data, 0, data.Length);







                while (true)
                {
                                   try
                    {
                      
                       
                            //nsClient.Flush();
                            recv = nsClient.Read(data, 0, data.Length);
                       
                        if (recv == 0)
                       {
                            break;
                        }
                      
                        strResponse = Encoding.ASCII.GetString(data, 0, recv);
                       
                        char[] delimit = new char[] { '\r', '\n' };
                        foreach (String sbReqs in strResponse.Split(delimit, StringSplitOptions.RemoveEmptyEntries))
                        {
                             SetText(sbReqs.ToString());
                        }
                       // dict.sorteer(strResponse);
                        nsProxy.Write(data, 0, data.Length);
                         }























     
                    catch (IOException e)
                    {
                        SetText("connection closed\n");
                        SetText("Reason:" + e.ToString());
                        break;
                    }
                    finally
                    {
                        nsClient.Flush();
                    }
                  
                   }
                   //nsClient.Close();
                   //tcClient.Close();
                   SetText("connection closed Client");
            }















            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                //listenerthread.Abort();
                //tlProxy.Stop();
                nsProxy.Close();
                nsClient.Close();
                tcProxy.Close();
                tcClient.Close();
            }








            private void Form1_FormClosing(object sender, EventArgs e)
            {

            }
        }
    }


     
























     

     Any tips will be appreciated.

Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Nine people can't make a baby in a month.” - Fred Brooks