HTTP 协议
Http protocol :Request/Response based,and stateless protocol(基于请求和响应的无状态协议),http 基本TCP/IP,需要对socket通信有一些理解。
HTTP通信的7步
1) 建立TCP/IP连接(Http/ftp 都是TCP/ip的上层协议,必须先建立)
2)Web browser 向Web Server 发送请求命令(例如:Get/sample/hello)
3)Web browser 发送Http Request Header
4)Web Server 应答(connection的状态等等)
5) web Server 发送Response Header
6)Web Server 返回Response Body
7)关闭TCP/IP (不知道下次用户操作的时间)
HTTP Server 代码实现(C#)
常用的web Server我们常用的web服务,是IIS,tomcat等。在进行网络通信的时候我们还会用到socket,甚至可以基于socket来实现HTTP通信,不过我们看一下更简单的实现。
using System;
using System.Net;
using System.Text;
using System.Threading;
namespace httpRequestTest
{
class Program
{
static void Main(string[] args)
{
var httpListener = new HttpListener();
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListener.Prefixes.Add("http://localhost/");
httpListener.Start();
var httpThread = new Thread(new ThreadStart((() =>
{
try
{
loop(httpListener);
}
catch (Exception e)
{
Console.WriteLine(e);
httpListener.Stop();
}
})));
httpThread.Start();
}
private static void loop(HttpListener httpListenner)
{
while (true)
{
HttpListenerContext context = httpListenner.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
Servlet servlet = new MyServlet();
servlet.onCreate();
if (request.HttpMethod == "POST")
{
servlet.onPost(request, response);
}
else if (request.HttpMethod == "GET")
{
servlet.onGet(request, response);
}
response.Close();
}
}
}
public class Servlet
{
public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
public virtual void onCreate()
{
}
}
public class MyServlet : Servlet
{
public override void onCreate()
{
base.onCreate();
}
public override void onGet(HttpListenerRequest request, HttpListenerResponse response)
{
Console.WriteLine("GET:" + request.Url);
byte[] buffer = Encoding.UTF8.GetBytes("OK");
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
//listener.Stop();
}
public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
{
Console.WriteLine("POST:" + request.Url);
byte[] res = Encoding.UTF8.GetBytes("OK");
response.OutputStream.Write(res, 0, res.Length);
}
}
}
HTTP Client 代码实现(C#)
案例:可以和上面的server 联调,理解完整的HTTP过程
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpClientDemo
{
class Program
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
HttpResponseMessage response = await client.GetAsync("http://localhost/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
Console.ReadKey();
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
}
Node.js Server 实现
通过案例可以看到Node.js对HTTP的封装更好,实现起来最方便
const http = require('http');
const server = http.createServer();
server.on('request',function(req,res){
console.log(req);
console.log(res);
});
server.listen(80,function(){
console.log('running http server');
});
client 可以使用 ajax 实现