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訪問