This article is a mirror article of machine translation, please click here to jump to the original article.

View: 22743|Reply: 0

[Source] Implement a simple Http service with HttpListener

[Copy link]
Posted on 12/2/2015 4:56:31 PM | | |
HttpListener provides a simple, programmable, and controllable HTTP protocol listener. It allows you to easily provide some Http services without having to start a large service program like IIS.

Note: This class is only available on computers running Windows XP SP2 or Windows Server 2003 operating systems.

The general steps to use Http services are as follows:

Create an HTTP listener object and initialize it
Add the URI prefix that needs to be listened to
Start listening for requests from clients
Handle Http requests from clients
Turn off the HTTP listener
Steps 3 and 4 can be cycled to provide services requested by multiple customers.

Create an HTTP listener object

To create an HTTP listener object, you only need to create a new HttpListener object.

HttpListener listener = new HttpListener();

Initialization requires the following two steps

You can add the URL range to listen to in listener.Prefixes by using the following function:
listener. Prefixes.Add(prefix) //prefix must end in '/'
Call listener. Start() to bind the port and start listening for the client's needs.
Accept HTTP requests

In .net 2.0, access to the request and response objects used by the HttpListener class is provided via the HttpListenerContext object.

The easiest way to get the HttpListenerContext is as follows:

HttpListenerContext context = listener. GetContext();

This method will block the call function until a client request is received, and if you want to improve the response speed, you can use the asynchronous method listener. BeginGetContext() to obtain the HttpListenerContext object.

Handle HTTP requests

After obtaining the HttpListenerContext, you can obtain the object that represents the client's request through the Request attribute and the object that represents the response that the HttpListener will send to the client through the Response attribute.

HttpListenerRequest request = context. Request;
HttpListenerResponse response = context. Response;

The HttpListenerRequest object here is similar to the use of Request and Response in Asp and HttpListenerResponse object, so I won't say much here, you can see the example below for specific use.

Turn off the HTTP listener

By calling listener. Stop() function to turn off the listener and free up the relevant resources

Code example:

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener. Prefixes.Add("http://localhost/"); Add the range of URLs that need to be listened to
            listener. Start(); Start listening on the port and receive client requests
            Console.WriteLine("Listening...");

            Blocks the main function until a client request is received
            HttpListenerContext context = listener. GetContext();
            HttpListenerRequest request = context. Request;
            HttpListenerResponse response = context. Response;

            string responseString = string. Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            Output the corresponding information to the client.
            response. ContentLength64 = buffer. Length;
            System.IO.Stream output = response. OutputStream;
            output. Write(buffer, 0, buffer. Length);
            Close the output stream to free up the corresponding resources
            output. Close();

            listener. Stop(); Turn off HttpListener
        }
    }
}

The program is relatively simple, first create an HTTP listener to implement the service of the "http://localhost/time/" domain, when it receives a remote request, it converts the current time into a string output to the client, and then closes the listener.





Previous:Problems and solutions for AJAX cross-domain calls to ASP.NET MVC or WebAPI services
Next:On December 3, 2015, the website was officially renamed &quot;Code Farmer Network&quot;, hereby notified!
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com