http要完成的任务
> The client opens a connection(客户端建立连接,此时服务器也在等待连接)
> The client sends a request (GET, HEAD, or POST) (客户端发起请求,告诉服务器要做的内容)
> The client waits for a response (客户端等待服务器的相应)
> The server processes the request (服务器处理客户端的请求,也就是三个方法)
> The server sends a response (服务器发送自己的结果,也就是所谓的响应)
> The connection is closed (关闭连接)
http协议把每次请求都当作与之前任何请求都无关的独立事务看待,即无状态协议http是应用层协议 需要传输层提供的服务
在python中socket提供对tcp和upd操作的接口
使用socket调用tcp服务为要实现的http提供稳定的连接
http默认线路是稳定的 tcp在实现稳定连接使用了三次握手和四次握手
http连接是短连接 过程为client发起连接请求,server响应内容 然后就断开
因此用socket调用tcp实现时socket完成请求后会调用close方法断开连接
用python的socket接口实现http的client端
#! /usr/bin/python2.7
import socket
# Address
HOST = '127.0.0.1'
PORT = 8882
request1 = '''GET /?a=1&b=2 HTTP/1.1
HOST:localhost:8882
'''
# configure socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# send message
s.sendall(request1)
# receive message
reply = s.recv(1024)
print 'reply is: ', reply
# close connection
s.close()
要实现post请求需要对请求头做下修改:
//请求头部 "POST url HTTP/1.1" "Host: 127.0.0.1\r\n"; "Content-Type:application/x-www-form-urlencoded\r\n"; //指定post传递的数据类型 "Content-Length: " + data.length() + "\r\n"; //标记post传递的数据的长度