Click here to Skip to main content
15,887,267 members
Home / Discussions / C#
   

C#

 
AnswerDo not cross post Pin
dan!sh 27-Oct-09 2:13
professional dan!sh 27-Oct-09 2:13 
GeneralRe: Do not cross post Pin
pallaka27-Oct-09 3:03
pallaka27-Oct-09 3:03 
GeneralRe: Do not cross post Pin
Not Active27-Oct-09 3:08
mentorNot Active27-Oct-09 3:08 
AnswerRe: How to plug/unplug USB serial port problematically? Pin
anishkannan27-Oct-09 8:36
anishkannan27-Oct-09 8:36 
Questioncrystal report error Pin
indenturetech27-Oct-09 2:01
indenturetech27-Oct-09 2:01 
QuestionAsynchronous Sockets Pin
joana.simoes27-Oct-09 1:44
joana.simoes27-Oct-09 1:44 
AnswerRe: Asynchronous Sockets Pin
Paulo Zemek27-Oct-09 3:04
mvaPaulo Zemek27-Oct-09 3:04 
GeneralRe: Asynchronous Sockets Pin
joana.simoes28-Oct-09 7:28
joana.simoes28-Oct-09 7:28 
Thanks for the advice! That was a really good suggestion.
I decided that I didnt need such a complicated solution; I didnt need one asynchronous listening socket and an asynchronous client socket;
In fact, all I need is a listening socket that is asynchronous (otherwise it will block the main thread) and I can stream the request in the same class (multithreading is not really an issue, since I wont have multiple requests to the server); I also found it much more convenient to use the HttpListener class;
Here is the code I ended up with:

using System;
using System.Text;
using System.Net;
using System.IO;

namespace TEST
{
    public delegate void delReceiveWebRequest(HttpListenerContext Context);

    public class ProxyServer
    {
        private int m_port = 47809;//Starts with this port, which according to IANA is for private use!
        private static string localhost = "127.0.0.1";
        const int BUFFER_SIZE = 1024;
        public string m_server;
        protected HttpListener m_listener;
        private CredentialCache m_credCache;
        public event delReceiveWebRequest ReceiveWebRequest;

        public ProxyServer(string server, CredentialCache credCache)
        {
            this.m_server = server;
            this.m_credCache = credCache;
        }

        public string Address()
        {
            return "http://" + localhost + ":" + m_port.ToString() + "/";
        }

        /// <summary>
        /// Starts the Web Service
        /// </summary>
        /// <param name="UrlBase">
        /// A Uri that acts as the base that the server is listening on.
        /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
        /// Note: the trailing backslash is required! For more info see the
        /// HttpListener.Prefixes property on MSDN.
        /// </param>

        public bool Start()
        {
            try
            {
                this.m_listener = new HttpListener();
                this.m_listener.Prefixes.Add(Address());
                this.m_listener.Start();

                IAsyncResult result = this.m_listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.m_listener);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                System.Diagnostics.Debug.WriteLine("Could not connect on port " + m_port.ToString() + "!");
                m_port++;
                return false;
            }

            System.Diagnostics.Debug.WriteLine("Listening socket on port " + m_port);
            return true;
        }

        /// <summary>
        /// Shut down the Web Service
        /// </summary>

        public void Stop()
        {
            if (m_listener != null)
            {
                this.m_listener.Close();
                this.m_listener = null;
                System.Diagnostics.Debug.WriteLine("Proxy stopped on port " + m_port.ToString() + "!");
            }
        }

        protected void WebRequestCallback(IAsyncResult result)
        {
            if (this.m_listener == null)
                return;

            // Get out the context object
            HttpListenerContext context = this.m_listener.EndGetContext(result);

            // *** Immediately set up the next context
            this.m_listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.m_listener);

            if (this.ReceiveWebRequest != null)
                this.ReceiveWebRequest(context);

            this.ProcessRequest(context);
        }

        protected virtual void ProcessRequest(HttpListenerContext Context)
        {
            string uri=Context.Request.RawUrl;

            this.m_server = this.m_server.Remove(this.m_server.Length - 1);
            string address = this.m_server + uri;
            WebRequest request = (HttpWebRequest)WebRequest.Create(address);
            request.Credentials = m_credCache;//CredentialCache.DefaultCredentials;
            StringBuilder RequestData = new StringBuilder(String.Empty);

            WebResponse myWebResponse = request.GetResponse();
            Stream ReceiveStream = myWebResponse.GetResponseStream();

            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            // Pipe the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[BUFFER_SIZE];

            // Read 1024 characters at a time.    
            int count = readStream.Read(read, 0, BUFFER_SIZE);

            HttpListenerResponse response = Context.Response;
            System.IO.Stream output = response.OutputStream;

            while (count > 0)
            {
                // Dump the 1024 characters on a string and display the string onto the console.
                String str = new String(read, 0, count);

                output.Write(encode.GetBytes(str), 0, encode.GetBytes(str).Length);
                count = readStream.Read(read, 0, BUFFER_SIZE);
            }

            output.Close();
        }
    }

}

AnswerRe: Asynchronous Sockets Pin
Jimmanuel27-Oct-09 5:00
Jimmanuel27-Oct-09 5:00 
Questionencrypt the app.config Pin
reza assar27-Oct-09 1:35
reza assar27-Oct-09 1:35 
AnswerRe: encrypt the app.config Pin
Pete O'Hanlon27-Oct-09 1:45
mvePete O'Hanlon27-Oct-09 1:45 
Questionlock some text files Pin
reza assar27-Oct-09 1:28
reza assar27-Oct-09 1:28 
AnswerRe: lock some text files Pin
Eddy Vluggen27-Oct-09 8:14
professionalEddy Vluggen27-Oct-09 8:14 
GeneralRe: lock some text files Pin
reza assar9-Nov-09 18:36
reza assar9-Nov-09 18:36 
GeneralRe: lock some text files Pin
Eddy Vluggen10-Nov-09 3:42
professionalEddy Vluggen10-Nov-09 3:42 
QuestionADO.NET Entity Framework Pin
Pankaj Saha27-Oct-09 1:27
Pankaj Saha27-Oct-09 1:27 
AnswerRe: ADO.NET Entity Framework Pin
Not Active27-Oct-09 2:12
mentorNot Active27-Oct-09 2:12 
Questionactive single instance only Pin
reza assar27-Oct-09 1:24
reza assar27-Oct-09 1:24 
AnswerRe: active single instance only Pin
N a v a n e e t h27-Oct-09 1:28
N a v a n e e t h27-Oct-09 1:28 
GeneralRe: active single instance only Pin
Hristo-Bojilov27-Oct-09 1:58
Hristo-Bojilov27-Oct-09 1:58 
GeneralRe: active single instance only Pin
N a v a n e e t h27-Oct-09 2:10
N a v a n e e t h27-Oct-09 2:10 
GeneralRe: active single instance only Pin
Hristo-Bojilov27-Oct-09 2:22
Hristo-Bojilov27-Oct-09 2:22 
GeneralRe: active single instance only Pin
Luc Pattyn27-Oct-09 4:16
sitebuilderLuc Pattyn27-Oct-09 4:16 
AnswerRe: active single instance only Pin
anishkannan27-Oct-09 1:47
anishkannan27-Oct-09 1:47 
AnswerRe: active single instance only Pin
vtchris-peterson28-Oct-09 5:43
vtchris-peterson28-Oct-09 5:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.