上一篇文章说了服务器如何给客户端发送一个字符串,这篇文章我们来说说,如何发送一个文章给客户端(浏览器)。
写一个socket的server端
#!/usr/bin/env python # coding:utf-8 import socket def handle_request(client): buf = client.recv(1024) # client.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding=‘utf-8‘)) # client.send(bytes("Hello, Seven",encoding=‘utf-8‘)) # 以二进制的方式打开文件 file = open(‘index.html‘,‘rb‘) # 读取文件的所有内容 data = file.read() file.close() # 把读取到的内容全部发送到客户端 client.send(data) def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((‘127.0.0.1‘, 8001)) sock.listen(5) while True: connection, address = sock.accept() handle_request(connection) connection.close() if __name__ == ‘__main__‘: main()
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello,Seven!</h1> <a href="http://www.jinlejia.com">走你</a> <table border="1"> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table> </body> </html>
本文出自 “学习改变命运” 博客,请务必保留此出处http://itzhongxin.blog.51cto.com/12734415/1913069
人生苦短,我学python之服务器如何返回一个文件内容到客户端
原文地址:http://itzhongxin.blog.51cto.com/12734415/1913069