首页 > 解决方案 > 使用 socket 模块提供 html

问题描述

我使用python套接字打开了端口8080:Sk.bind(ip_addrr,8080)但我希望它在该端口中打开一个html页面,这样当我在浏览器中导航到:8080时,我必须得到一个网页。有什么想法吗?

我的问题是我需要获得一个我创建的 html 页面,以显示在端口 8080 中。例如,我有类似的端口 80 的 index.html,我需要在端口 8080 中有一个 html 页面。我将如何做到这一点?

标签: htmllinuxpython-sockets

解决方案


经过一些研究,我能够整理出非常小的例子。您也可以在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。


推荐阅读