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