Python 實現(xiàn)一個簡單的web服務(wù)器
更新時間:2021年01月03日 09:22:49 作者:凌冷
這篇文章主要介紹了Python 實現(xiàn)一個簡單的web服務(wù)器的方法,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
import re
import socket
def service_cilent(new_socket):
request = new_socket.recv(1024).decode("utf-8")
# Python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表,如果參數(shù) keepends 為 False,不包含換行符,如果為 True,則保留換行符。
request_lines = request.splitlines()
print(request_lines)
file_name = ""
ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = "index.html"
try:
f = open(file_name, "rb")
except:
response = "HTTP/1.1 404 NOT FOUND\r\n\r\n"
response += "------file not found-----"
new_socket.send(response.encode("utf-8"))
else:
# 打開文件成功就讀文件 然后關(guān)閉文件指針
html_content = f.read()
f.close()
# 準(zhǔn)備發(fā)送給瀏覽器的數(shù)據(jù)---header
response = "HTTP/1.1 200 OK\r\n\r\n"
# 將response header發(fā)送給瀏覽器
new_socket.send(response.encode("utf-8"))
# 將response body發(fā)送給瀏覽器
new_socket.send(html_content)
# 關(guān)閉套接字
new_socket.close()
def main():
# 創(chuàng)建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 綁定
tcp_server_socket.bind(("", 7089))
# 監(jiān)聽套接字
tcp_server_socket.listen(128)
while True:
new_socket, cilent_addr = tcp_server_socket.accept()
service_cilent(new_socket)
# 關(guān)閉監(jiān)聽套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()
以上就是Python 實現(xiàn)一個簡單的web服務(wù)器的詳細(xì)內(nèi)容,更多關(guān)于python 實現(xiàn)web服務(wù)器的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- Python Tornado實現(xiàn)WEB服務(wù)器Socket服務(wù)器共存并實現(xiàn)交互的方法
- Python Web靜態(tài)服務(wù)器非堵塞模式實現(xiàn)方法示例
- python3實現(xiàn)微型的web服務(wù)器
- Python面向?qū)ο笾甒eb靜態(tài)服務(wù)器
- python實現(xiàn)靜態(tài)web服務(wù)器
- Tornado Web Server框架編寫簡易Python服務(wù)器
- Python Web程序部署到Ubuntu服務(wù)器上的方法
- python快速建立超簡單的web服務(wù)器的實現(xiàn)方法
- Python實現(xiàn)簡易版的Web服務(wù)器(推薦)
- python探索之BaseHTTPServer-實現(xiàn)Web服務(wù)器介紹
相關(guān)文章
pycharm中使用request和Pytest進行接口測試的方法
這篇文章主要介紹了pycharm中使用request和Pytest進行接口測試的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
windows10在visual studio2019下配置使用openCV4.3.0
這篇文章主要介紹了windows10在visual studio2019下配置使用openCV4.3.0,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

