views:

73

answers:

1

Hello

I am writing a web service which has to be able to reply to multiple http requests. From what I understand, I will need to deal with HttpListener. What is the best method to receive a http request(or better, multiple http requests), translate it and send the results back to the caller? How safe is to use HttpListeners on threads?

Thanks

A: 

You typically set up a main thread that accepts connections and passes the request to be handled by either a new thread or a free thread in a thread pool. I'd say you're on the right track though.

You're looking for something similar to:

 while (boolProcessRequests)
            {
                HttpListenerContext context = null;
                    // this line blocks until a new request arrives
                   context = listener.GetContext();
                   Thread T = new Thread((new YourRequestProcessorClass(context)).ExecuteRequest);
                   T.Start();
         }

Edit Detailed Description If you don't have access to a web-server and need to roll your own web-service, you would use the following structure:

One main thread that accepts connections/requests and as soon as they arrive, it passes the connection to a free threat to process. Sort of like the Hostess at a restaurant that passes you to a Waiter/Waitress who will process your request.

In this case, the Hostess (main thread) has a loop: - Wait at the door for new arrivals - Find a free table and seat the patrons there and call the waiter to process the request. - Go back to the door and wait.

In the code above, the requests are packaged inside the HttpListernContext object. Once they arrive, the main thread creates a new thread and a new RequestProcessor class that is initialized with the request data (context). The RequsetProcessor then uses the Response object inside the context object to respond to the request. Obviously you need to create the YourRequestProcessorClass and function like ExecuteRequest to be run by the thread.

I'm not sure what platform you're on, but you can see a .Net example for threading here and for httplistener here.

MandoMando
Thanks for the answer. Could you please give some more informations about the whole process logic?
phm
@phm to simplify things further, you can also look at ParametereizedThreadStart to use instead of the (new YourRequestProcessorClass(context)).ExecuteRequest bit.
MandoMando
thanks. That was a good info
phm