如何在服務器上運行python程序,python實現簡單的http服務器_python實現簡單http服務器功能

 2023-12-06 阅读 39 评论 0

摘要:背景如何在服務器上運行python程序、寫一個python腳本,實現簡單的http服務器功能:1.瀏覽器中輸入網站地址:172.20.52.163:20014python服務器搭建。2.server接到瀏覽器的請求后,讀取本地的index.html文件的內容,回發給瀏覽器代碼實現server

背景

如何在服務器上運行python程序、寫一個python腳本,實現簡單的http服務器功能:

1.瀏覽器中輸入網站地址:172.20.52.163:20014

python服務器搭建。2.server接到瀏覽器的請求后,讀取本地的index.html文件的內容,回發給瀏覽器

代碼實現

server.py

#!/usr/bin/python

import socket

import signal

import errno

from time import sleep

def HttpResponse(header,whtml):

f = file(whtml)

contxtlist = f.readlines()

context = ''.join(contxtlist)

response = "%s %dnn%snn" % (header,len(context),context)

return response

def sigIntHander(signo,frame):

print 'get signo# ',signo

global runflag

runflag = False

global lisfd

lisfd.shutdown(socket.SHUT_RD)

strHost = "172.20.52.163"

HOST = strHost #socket.inet_pton(socket.AF_INET,strHost)

PORT = 20014

httpheader = '''

HTTP/1.1 200 OK

Context-Type: text/html

Server: Python-slp version 1.0

Context-Length: '''

lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

lisfd.bind((HOST, PORT))

lisfd.listen(2)

signal.signal(signal.SIGINT,sigIntHander)

runflag = True

while runflag:

try:

confd,addr = lisfd.accept()

except socket.error as e:

if e.errno == errno.EINTR:

print 'get a except EINTR'

else:

raise

continue

if runflag == False:

break;

print "connect by ",addr

data = confd.recv(1024)

if not data:

break

print data

confd.send(HttpResponse(httpheader,'index.html'))

confd.close()

else:

print 'runflag#',runflag

print 'Done'

index.html

Python Server

Hello python

Welcom to the python world

測試

測試結果:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py

connect by? ('172.20.52.110', 6096)

GET / HTTP/1.1

Host: 172.20.52.163:20014

Connection: keep-alive

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36

Accept-Encoding: gzip,deflate,sdch

Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

瀏覽器

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/189021.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息