html - 使用 socket 模块提供 html
问题描述
我使用python套接字打开了端口8080:Sk.bind(ip_addrr,8080)但我希望它在该端口中打开一个html页面,这样当我在浏览器中导航到:8080时,我必须得到一个网页。有什么想法吗?
我的问题是我需要获得一个我创建的 html 页面,以显示在端口 8080 中。例如,我有类似的端口 80 的 index.html,我需要在端口 8080 中有一个 html 页面。我将如何做到这一点?
解决方案
经过一些研究,我能够整理出非常小的例子。您也可以在https://replit.com/@bluebrown/python-socket-html上找到它
import socket
s = socket.socket()
s.bind(('0.0.0.0', 8080))
s.listen(1)
with open('index.html', 'rb') as file:
html = file.read()
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
req = conn.recv(1024)
print('request:', req)
conn.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
conn.sendall(html)
根据您在他的评论中的要求,我已经采取了更进一步的措施。不过不多。足以让您了解如何为不同的页面提供服务。
import socket
def parseRequest(request):
output = {}
r = request.decode("utf-8").split("\r\n")
parts = r[0].split(' ')
output["method"] = parts[0]
output["path"] = parts[1]
output["protocol"] = parts[2]
output["headers"] = { (kv.split(':')[0]): kv.split(':')[1].strip() for kv in r[1:] if (len(kv.split(':')) > 1) }
return output
s = socket.socket()
s.bind(('0.0.0.0', 8080))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
req = conn.recv(1024)
r = parseRequest(req)
path = r["path"][1:]
if (path == ""):
path = "index"
with open(f'{path}.html', 'rb') as file:
html = file.read()
conn.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
conn.sendall(html)
您可以检查更新的repl。
推荐阅读
- python-3.x - 在 python 3 中使用 subprocess.check_call 运行 Oracle DBCA
- c# - 如何使用 Microsoft.Identity.Web 对 Azure.Storage.Blobs 进行授权?
- sql-server - Scriptella - SQLServerException:为更新生成了结果集
- excel - 如何创建一个仅自动从第二个列表中提取唯一实例的列表 - 即使第二个列表已更改?
- php - 在 mysql 查询中选择前一个值
- php - Laravel 弹性搜索在安装时返回分配的内存超出错误
- javascript - URL 值与 javascript 中的字符串值不匹配
- python - Flask->有没有其他方法可以在不提交数据库的情况下使用flask_login的login_user?
- flutter - Flutter 无法加载资产:但目录不存在
- biztalk - BizTalk 中的请求响应发送端口和管道