一、用socket来模拟网站访问
socket为python2.7 #!/usr/bin/env python # -*- coding:utf-8 -*- import socket def handle_request(client): buf = client.recv(1024) client.send("HTTP/1.1 200 OK ") f = open("demo.html", "r") data = f.read() f.close() client.send(data) def main(): ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ss.bind(("127.0.0.1", 8003)) ss.listen(5) while True: connection, address = ss.accept() handle_request(connection) connection.close() if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding:utf-8 -*- import socket def handle_request(client): client.sendall(bytes("HTTP/1.1 200 OK ", encoding="utf-8")) buf = str(client.recv(1024),encoding="utf-8") # f = open("demo.html", "r") # data = f.read() # f.close() data='<h1>666</h1>' client.sendall(bytes(str(data),encoding="utf-8")) def main(): ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ss.bind(("127.0.0.1", 8003)) ss.listen(5) while True: connection, address = ss.accept() handle_request(connection) connection.close() if __name__ == '__main__': main()
上面就是模拟用户访问socket之后返回给用户的信息,这份信息是字符串,来源于demo.html
程序员修改网页信息只需要写好页面添加进服务器就可以
其中nginx和apache服务就是这样的原理