您好,登錄后才能下訂單哦!
這篇文章主要介紹python如何實(shí)現(xiàn)簡(jiǎn)單http服務(wù)器功能,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
背景
寫一個(gè)python腳本,實(shí)現(xiàn)簡(jiǎn)單的http服務(wù)器功能:
1.瀏覽器中輸入網(wǎng)站地址:172.20.52.163:20014
2.server接到瀏覽器的請(qǐng)求后,讀取本地的index.html文件的內(nèi)容,回發(fā)給瀏覽器
代碼實(shí)現(xiàn)
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 %d\n\n%s\n\n" % (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
<html> <head> <title>Python Server</title> </head> <body> <h2>Hello python</h2> <p>Welcom to the python world</br> </body> </html>
測(cè)試
測(cè)試結(jié)果:
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
瀏覽器
以上是“python如何實(shí)現(xiàn)簡(jiǎn)單http服務(wù)器功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。