El servicio de socket lee el archivo index.html

Servidor de socket de compilación de Python, especifique el puerto 8000, lea el contenido del archivo especificado index.html

  • servidor de socket
import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding='utf-8'))
    # 打开index.html文件读取内容
    f  = open('index.html',mode='rb')
    data = f.read()
    f.close()
    client.send(data)

def main():
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(('localhost',8000)) #监听8000端口
    sock.listen(100)

    while True:
        connection,address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>socket_test</title>
    <h1 style="color:green">It's what the socket reads from the HTML file.</h1>
</head>
<body>

</body>
</html>
  • Inicie el programa, ingrese 127.0.0.1:8000 en el navegador para acceder
    Inserte la descripción de la imagen aquí
141 artículos originales publicados · Me gusta 318 · Visita 270,000+

Supongo que te gusta

Origin blog.csdn.net/Sunny_Future/article/details/105449033
Recomendado
Clasificación