socket和tcp协议编写的基于HTTP协议的web服务器
from socket import *
def request_handler(clinent_socket):
recv_data = clinent_socket.recv(1024)
if not recv_data:
clinent_socket.close()
return
response_line = "HTTP/1.1 200 OK\r\n" # 响应行
response_header = "Server:python2020\r\n" # 响应头
response_blank = '\r\n' # 空行
response_body = "<h1>hello this is a python web server</h1>\r\n" # 响应内容
response_data = (response_line + response_header + response_blank + response_body).encode('GBK')
return response_data
def main():
tcp_server_socket = socket(AF_INET, SOCK_STREAM)
address = ("", 7788)
tcp_server_socket.bind(address)
tcp_server_socket.listen(128)
while True:
clinent_socket, ip_port = tcp_server_socket.accept()
print('连接的对象是:%s,ip:%s,port:%s'%(clinent_socket,ip_port[0],ip_port[1]))
clinent_socket.send(request_handler(clinent_socket))
clinent_socket.close()
if __name__ == '__main__':
main()
效果如图