网站服务器如何处理客户端请求,在HTTP服务器中处理客户端请求

importsocketimportos.path

IP="127.0.0.1"PORT=80DEFAULT_URL="C:\webroot\index.html"SOCKET_TIMEOUT=0.2defget_file_data(filename):""" Get data from file """source_file=open(filename,'rb')data=source_file.read()source_file.close()returndatadefhandle_client_request(resource,client_socket):""" Check the required resource, generate proper HTTP response and send to client"""ifresource=='/':url=DEFAULT_URLelse:url=resourceifos.path.isfile(url):http_header="HTTP/1.0 200 OK\r\n"else:client_socket.send("404 (Not Found)\r\n"+"connection close")client_socket.close()file_type=url.split(".")[-1]iffile_type=='html'orfile_type=='txt':http_header+="Content-Type: text/html; charset=utf-8\r\n"eliffile_type=='jpg':http_header+="Content-Type: image/jpeg\r\n"eliffile_type=='js':http_header+="Content-Type: text/javascript; charset=UTF-8\r\n"eliffile_type=='css':http_header+="Content-Type: text/css\r\n"data=get_file_data(url)http_header+="Content-Length:"+str(len(data))+"\r\n"http_response=http_header+"\r\n"+data

client_socket.send(http_response)defvalidate_http_request(request):""" Check if request is a valid HTTP request and returns TRUE / FALSE and the requested URL """request_li=request.split("\r\n")[0].split(" ")ifrequest_li[0]!="GET"orrequest_li[2]!="HTTP/1.1"'/':returnFalse,''returnTrue,request_li[1]defhandle_client(client_socket):""" Handles client requests: verifies client's requests are legal HTTP, calls function to handle the requests """print'Client connected'try:whileTrue:client_request=client_socket.recv(1024)printclient_request.split("\r\n")[0]valid_http,resource=validate_http_request(client_request)ifvalid_http:print'Got a valid HTTP request'handle_client_request(resource,client_socket)else:print"Error: HTTP request isn't valid"breakprint"closing connection"client_socket.close()exceptsocket.timeout:print"closing connections"client_socket.close()defmain():server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)server_socket.bind((IP,PORT))server_socket.listen(10)print"Listening for connections on port %d"%PORTwhileTrue:client_socket,client_address=server_socket.accept()client_socket.settimeout(SOCKET_TIMEOUT)print'New connection received'handle_client(client_socket)if__name__=="__main__":main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值