python socket实现简单的web服务器

xxx.py
# coding:utf-8 import socket ip_port = ('127.0.0.1',8080) back_log = 10 buffer_size = 1024 alldata = "<h1>Hello World</h1>" def main(): webserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) webserver.bind(ip_port) webserver.listen(back_log) print("waiting for connection...............") while True: conn, addr = webserver.accept() print(addr) recvdata = conn.recv(buffer_size) conn.sendall(bytes("HTTP/1.1 201 OK\r\n\r\n", "utf-8")) # 响应头 # conn.sendall(bytes(alldata, "utf-8")) conn.sendall(bytes(alldata, "utf-8")) with open("1.html","rb") as f: data = f.read() # conn.sendall(bytes("HTTP/1.1 201 OK\r\n\r\n", "utf-8")) # 响应头 conn.sendall(data) conn.close() if __name__ == '__main__': main()
1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>welcome</h1> <h1>hello ,this is my web server</h1> </body> </html>

运行.py文件,浏览器输入:

http://127.0.0.1:8080/

最终结果:

posted @ 2019-12-26 17:48  腹肌猿  阅读(1194)  评论(0编辑  收藏  举报