python循环接收http请求数据
最近做一个项目需要测试http请求,大量密集的http请求测试,网上只找到了postman这种client工具,没有发现http server工具,于是想手写一个。
听闻python快捷,网上找了一个,但是只能接收一次数据,于是改动了一下,测试了一下效果还不错,这里记录一下。
# coding:utf-8 #环境:python2.7 import socket from multiprocessing import Process if __name__ == "__main__": server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 8000)) server_socket.listen(128) client_socket, client_address = server_socket.accept() while True: request_data = client_socket.recv(10240) print("request data:", request_data) # 构造响应数据 response_start_line = "HTTP/1.1 200 OKrn" response_headers = "Server: receivedrn" response_body = "Python HTTP Test
" response = response_start_line + response_headers + "rn" + response_body # 向客户端返回响应数据 client_socket.send(bytes(response))
python获取http请求报文数据
import socket if __name__ == '__main__': # 1.创建tcp服务端套接字 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2.绑定端口(端口号可以修改) tcp_server_socket.bind(("", 8989)) # 3.等待接收客户端的连接请求 service_client_socket, ip_port = tcp_server_socket.accept() print(ip_port) # 4.接收客户端发送的http请求报文数据 recv_fata = service_client_socket.recv(4096) # 5.显示原始http请求报文数据 print(recv_data) service_clinent_socket.close() tcp_server_socket.close()
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。