Take the multithreaded Programming learning notes above--using asynchronous IO
Second, write an asynchronous HTTP server and client
This section shows how to write a simple asynchronous HTTP server.
1. The program code is as follows.
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Text;usingSystem.Threading.Tasks;namespacethreadiodemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("--Create a simple Web service sample--"); varServer =NewAsynchttpserver (Port:1234); vart = Task.run (() =server. Start ()); Console.WriteLine ("Listening on port 1234. Open the http://localhost:1234 in the browser"); Console.WriteLine ("Test Connection"); Console.WriteLine (); Getresponseasync ("http://localhost:1234"). Getawaiter (). GetResult (); Console.WriteLine (); Console.WriteLine ("Enter a enter key to stop the service"); Console.ReadLine (); stringmsg=server. Stop (). Getawaiter (). GetResult (); Console.WriteLine (msg); Console.read (); } Static AsyncTask Getresponseasync (stringURL) { using(varClient =NewHttpClient ()) {Httpresponsemessage Responsemessage=awaitclient. Getasync (URL); stringResponseheaders =responseMessage.Headers.ToString (); stringResponse =awaitResponseMessage.Content.ReadAsStringAsync (); Console.WriteLine ("Response Headers:"); Console.WriteLine (responseheaders); Console.WriteLine ("Response Body:"); Console.WriteLine (response); } } } classAsynchttpserver {ReadOnlyHttpListener _listener; Const stringResponse_template ="<body>"; PublicAsynchttpserver (intPort) {_listener=NewHttpListener (); _listener. Prefixes.add (string. Format ("http://+:{0}/", port)); } Public AsyncTask Start () {_listener. Start (); while(true) { varCTX =await_listener. Getcontextasync (); Console.WriteLine ("{0} Client connected ...", DateTime.Now.ToString ()); stringResponse =string. Format (Response_template, DateTime.Now); using(varSW =NewStreamWriter (CTX. Response.outputstream)) {awaitSW. WriteAsync (response); awaitSW. Flushasync (); } } //return string. Format ("Listener service start {0}", DateTime.Now.ToString ()); } Public Asynctask<string>Stop () {_listener. Stop (); Console.WriteLine ("Listen stop, stop the service"); awaitTask.delay (Timespan.fromseconds (2)); return string. Format ("Listener service stopped {0}", DateTime.Now.ToString ()); } }}
The 2.http service starts as.
3. Enter http://localhost:1234 in the browser, followed by 1. After waiting for 30 seconds, refresh again, as in 2.
4. In the HTTP Web service program, you can see that the browser has accessed the server two times. As in the red box.
4. Enter the carriage return in the HTTP Web service program and the service will stop. As in the red box.
Here we implement a very simple Web server through the HttpListener class. The TcpListener class is also used for TCP socket I/O operations. We configured the listener to receive connections from any host to the local machine 1234 port. This monitor is then launched in a separate worker thread, allowing the listener to be controlled in the main thread.
asynchronous I/O operations occur when the Getcontextasync method is used. Unfortunately, it does not receive cancellationtoken to implement the cancellation function. So if you want to shut down this server, you only need to call _listenter. Abort method, which discards all connections and shuts down the server.
To perform an asynchronous request to this server, we used the HttpClient class in the System.Net.Http collection under the unified namespace. We use the Get.async method to initiate an asynchronous HTTP GET request. There are other ways to initiate other HTTP requests, such as Post,delete,put. HttpClient also has many other options, such as serializing and deserializing objects using different formats (such as XML and JSON), specifying proxy server addresses, authentication, and other configurations.
When you run this program, you can see that the server is started up. In server-side code, we use the Getcontextasync method to receive new client connections. This method returns when there is a new client connection. We simply output a very basic HTML that contains the current date and time as a response. Then we request the service and print the response header and content.
Multithreaded Programming Learning notes-writing an asynchronous HTTP server and client