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文件,浏览器输入:
最终结果:
标签:__,web,utf,socket,python,bytes,sendall,conn 来源: https://www.cnblogs.com/pfeiliu/p/12103480.html