繁体   English   中英

如何使用 sockets 在本地网络服务器中响应对 favicon.ico 的 GET 请求

[英]How to respond to a GET request for favicon.ico in a local webserver using sockets

我已经使用 python 及其内置模块 sockets 创建了自己的网络服务器,现在当我运行代码时浏览器要求favicon.ico之前我正在静音它,但现在我决定给浏览器一个favicon.ico文件,但它似乎没有工作

服务器.py

...
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8000


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
...
while True:
    client_connection, client_address = server_socket.accept()
    request = client_connection.recv(1024).decode()
    ...

    response = 'HTTP/1.1 200 OK\r\n'
    # the code here is a little bit clustered, I will fix it when I solve this favicon problem
    if filename == '/':
        filename = '/index.html'
    if filename != "/favicon.ico":
        response += "Content-Type: text/html\r\n"
        with open(f"htdocs/{filename}") as f:
            data = f.read()
        response += f"Content-Length: {len(data)}\r\n\r\n{data}"
        client_connection.sendall(response.encode())
    else:
        with open(f"htdocs/{filename}", "rb") as f:
            data = f.read()
        response += f"Content-Type: image/x-icon\r\nContent-Length: {len(data)}\r\n\r\n"
        response += (base64.b64encode(data)).decode('utf-8')
        client_connection.sendall(response.encode())
    client_connection.close()

文件夹结构

/Webserver$ ls
htdocs  server.py  venv
/Webserver$ ls htdocs
favicon.ico  home.html  index.html

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>Index</title>
      <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>Welcome to the index.html web page..</p>
    <p>Here's a link to <a href="home.html">home</a></p>
  </body>
</html>

在此处输入图像描述 在这里, favicon.ico甚至作为image/x-icon发送,但没有显示。

htdocs/favicon.ico的尺寸为 16x16

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM