python3实现微型的web服务器

å®éªç®çï¼ç¨socket æ¨¡æä¸ä¸ªå¾®åçwebæå¡å¨ï¼å½pyèæ¬runèµ·åï¼å®å¾®åweb serveræ¶èµ·äºï¼ç¶åç¨æ¬å°æµè§å¨è®¿é®127.0.0.1:8080(web serverçip_port)æ¶webæå¡å¨å°±ä¼å°ç½é¡µå容传ç»æµè§å¨ï¼å®ç°ç½é¡µæµè§. 

sw+sys: python3.7.2 + windows10 64bit

æ¬å°åå¤çserver端ç½é¡µä¸ºä¸è½½çhao123主页ï¼æå·²ä¸è½½å¹¶ä¸ä¼ ï¼ç¹å»è¿éï¼

éè¿è¿ä¸ªå®éªè®©æå­¦å°äºï¼

1. å½get请æ±ä¸ä¸ªä¸»é¡µæ¶ï¼è¦å®æ´çæ¾ç¤ºä¸ä¸ªé¡µé¢ï¼åæ¬ææ¬ãå¾çãcssç»æç­ï¼æ¯è¦getå¤æ¬¡è¯·æ±çã

2. responeåå¤æ¬å°é¡µç½ï¼open(filepath, rwa)æ¶è¦ç¹å«ç注æ

import socket
import os
 
curfilepath = os.path.split(os.path.realpath(__file__))[0].replace("\\" , "/")
print(f'curfilepath: {curfilepath}')
 
 
def new_socket_server(new_socket, new_addr):
 if new_addr[0] != '':
  print(f'å½å客æ·ç«¯{new_addr}å·²è¿æ¥ä¸server端. ')
 
 # 3.æ¥æ¶ä¿¡æ¯
 file_name = ''
 request_data = new_socket.recv(1024).decode('utf-8')
 if request_data != '':
  print(f'ææ¶å°æ°çä¿¡æ¯ï¼ä¿¡æ¯å¦ä¸:\n{request_data}')
  file_name = request_data.splitlines()[0].split(' ')[1]
  print(f'file_name: {file_name}')
  if file_name == '/':
   file_name = '/index.html'
   print(f'file_name: {file_name}')
  with open(curfilepath + '/test.txt', 'a+') as f:
   f.write(file_name + '\n')
 
 # 4.åå¤ä¿¡æ¯
 try:
  f = open(curfilepath + '/htmltest' + file_name, 'rb')
 except:
  response = 'HTTP/1.1 404 NOT FOUND\r\n'
  response += '\r\n'
  response += '----------file not found-------'
  new_socket.send(response.encode('utf-8'))
 else:
  html_content = f.read()
  f.close()
  response = 'HTTP/1.1 200 OK\r\n' + '\r\n'
  new_socket.send(response.encode('utf-8'))
  new_socket.send(html_content)
 
 
def main():
 # 1.å建socket
 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
 # 2.è¿æ¥server
 server_ip_port = ('127.0.0.1', 8080)
 tcp_server_socket.bind(server_ip_port)
 tcp_server_socket.listen(128)
 while True:
  print('æ­£å¨ç­å¾client端è¿æ¥... ...')
  new_socket, new_addr = tcp_server_socket.accept()
  new_socket_server(new_socket, new_addr)
  new_socket.close()
 
 
if __name__ == '__main__':
 main()

以ä¸å°±æ¯æ¬æçå¨é¨å容ï¼å¸æ对大家ç学习ææ帮å©ï¼ä¹å¸æ大家å¤å¤æ¯æèæ¬ä¹å®¶ã

相关推荐