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/

最终结果:

python socket实现简单的web服务器

相关文章:

  • 2021-11-03
  • 2021-11-03
  • 2018-01-29
  • 2021-11-03
  • 2021-11-13
  • 2021-11-29
  • 2021-12-02
  • 2021-09-02
猜你喜欢
  • 2021-11-03
  • 2021-12-20
  • 2022-01-05
  • 2021-12-27
  • 2022-01-01
  • 2021-12-16
  • 2021-11-03
  • 2021-12-17
相关资源
相似解决方案