通过:127.0.0.1:8000 来访问
发送字符串
# 用socket实现一个简单的服务器,可以通过浏览器来访问 import socket def handle(conn): # 请求处理函数 data = conn.recv(1024) print(data) conn.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8")) conn.send(bytes("<h1>hello world<h1>",encoding="utf-8")) def main(): server = socket.socket() server.bind(("localhost", 8000)) server.listen(5) print("服务启动") while True: conn, addr = server.accept() print(conn, addr) handle(conn) conn.close() if __name__ == "__main__": main() """data GET / HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding: gzip, deflate, sdch, br Accept-Language: zh-CN,zh;q=0.8 Cookie: csrftoken=u8AqdKAvfHiF0To5s8p3Dqxec2uSWldxnOOpOEbUVLPHTWVWDSUck4zFjNPxjV8V """
显示效果
# 改进版服务器,可以从文件中读取文件并发送给客户端 import socket def handle(conn): buf = conn.recv(1024) conn.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8")) f = open("index.html", "rb") data = f.read() f.close() conn.send(data) def main(): server = socket.socket() server.bind(("localhost", 8000)) server.listen(5) print("服务启动") while True: conn, addr = server.accept() print(conn, addr) handle(conn) conn.close() if __name__ == "__main__": main()
显示效果
# 改进版服务器,可以从文件中读取文件并替换变量 发送给客户端 import socket import time def handle(conn): buf = conn.recv(1024) conn.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8")) f = open("index.html", "r") data = f.read() f.close() now_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) html = data.replace("{{time}}", now_time) conn.send(bytes(html, encoding="utf-8")) def main(): server = socket.socket() server.bind(("localhost", 8000)) server.listen(5) print("服务启动") while True: conn, addr = server.accept() print(conn, addr) handle(conn) conn.close() if __name__ == "__main__": main()
显示效果
刚刚的{{ time }} 被替换为了当前时间