代码如下所示:
import socket import re import multiprocessing def service_client(client_socket): data = client_socket.recv(1024) recv_data=data.decode("utf-8") print(recv_data) #GET /index.html HTTP/1.1 ret=re.match(r"[^/]+ /([\S]+\s|\s)",recv_data) file_n="index.html" if ret: if ret.group(1)!=" ": print(ret.group(1)) file_n=ret.group(1) else: print("代码有误!") try: with open(file_n,"rb") as f: content=f.read() f.close() except Exception as r: print(r) content = "<h1>file not found<\h1>".encode("utf-8") header="HTTP/1.1 200 OK\r\n" empty="\r\n" response=(header+empty).encode('utf-8') client_socket.send(response) client_socket.send(content) client_socket.close() print("client_socket.close()已调用") def main(): tcp_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) local_addr=("127.0.0.1",7788) tcp_socket.bind(local_addr) tcp_socket.listen(128) while True: client_socket, client_addr = tcp_socket.accept() p=multiprocessing.Process(target=service_client,args=(client_socket,)) p.start() # p.join() tcp_socket.close() if __name__ == "__main__": main()
注意:
1.开始的时候file_n没有先定义,结果就报错:local variable ‘file_n' referenced before assignment
2.正则表达式一定要先验证筛取的内容是否正确。
3.要获取程序同级文件夹中文件夹的文件,相对路基为“文件夹名/文件名”
4.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 要加不然容易出现“address already in use"之类的故障
总结
以上所述是小编给大家介绍的使用浏览器访问python写的服务器程序,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对IIS7站长之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!