Multi-thread programming learning notes-write an asynchronous HTTP server and client, multi-thread programming learning notes

Source: Internet
Author: User

Multi-thread programming learning notes-write an asynchronous HTTP server and client, multi-thread programming learning notes

Multi-thread programming learning notes-use Asynchronous IO

 

2. Compile an asynchronous HTTP server and client

This section describes how to write a simple asynchronous HTTP server.

1. The program code is as follows.

Using System; using System. collections. generic; using System. IO; using System. linq; using System. net; using System. net. http; using System. text; using System. threading. tasks; namespace ThreadIODemo {class Program {static void Main (string [] args) {Console. writeLine ("-- create a simple Web service example --"); var server = new AsyncHttpServer (port: 1234); var t = Task. run () => server. start (); Console. writeLine ("Listening on port 1234. open in a browser http://localhost:1234 "); Console. WriteLine (" test connection "); Console. WriteLine (); GetResponseAsync (" http://localhost:1234 "). GetAwaiter (). getResult (); Console. writeLine (); Console. writeLine ("Enter the Enter key to stop the service"); Console. readLine (); string msg = server. stop (). getAwaiter (). getResult (); Console. writeLine (msg); Console. read ();} static async Task GetResponseAsync (string url) {using (var client = new HttpClient () {HttpResponseMessage responseMessage = await client. getAsync (url); string responseHeaders = responseMessage. headers. toString (); string response = await responseMessage. content. readAsStringAsync (); Console. writeLine ("Response Headers:"); Console. writeLine (responseHeaders); Console. writeLine ("Response Body:"); Console. writeLine (response) ;}} class AsyncHttpServer {readonly HttpListener _ listener; const string RESPONSE_TEMPLATE = "<Body> 

 

2. Start the http service, as shown in figure.

 

3. Enter http: // localhost: 1234 in the browser, as shown in figure 1. Wait 30 seconds and refresh again, as shown in figure 2.

 

4. In the http web service program, you can see that the browser has accessed the server twice. As shown in the red box.

 

4. Enter a carriage return in the http web service program to stop the service. As shown in the red box.

 

Here we use the HTTPListener class to implement a very simple WEB server. The TCPLISTENER class is also used for TCP socket I/O operations. We configured the listener to receive connections from any host to port 1234 on the local machine. Then start the supervisor in a separate working thread to control the listener in the main thread.

Asynchronous I/O operations occur when the GetContextAsync method is used. Unfortunately, it does not receive CancellationToken to cancel the function. To disable the server, you only need to call the _ listenter. Abort method, which discards all connections and closes the server.

To execute an asynchronous request to this server, we use the HttpClient class in the unified namespace System. Net. Http set. We use the Get. Async method to initiate an asynchronous Http Get request. Other methods are used to initiate other HTTP requests, such as POST, DELETE, and PUT. HttpClient has many other options, such as serialization and deserialization of objects in different formats (such as XML and JSON), specifying the proxy server address, authentication, and other configurations.

When running this program, we can see that the server is started. In the server code, we use the GetContextAsync method to receive new client connections. This method is returned when a new client is connected. We simply output an HTML containing the current date and time as a response. Then we request the service and print the response header and content.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.