socket服務讀取文件index.html

python搭建socket服務端,指定端口8000,讀取內容指定文件index.html

  • 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>
  • 啓動程序,瀏覽器輸入127.0.0.1:8000訪問
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章