socket实现http

来源:互联网 发布:java单例模式实例 编辑:程序博客网 时间:2024/06/01 20:58
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.7import socket# AddressHOST = '127.0.0.1'PORT = 8882request1 = '''GET /?a=1&b=2 HTTP/1.1HOST:localhost:8882 '''# configure sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))# send messages.sendall(request1)# receive messagereply = s.recv(1024)print 'reply is: ', reply# close connections.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传递的数据的长度


 
原创粉丝点击