python连接服务器失败_Python HTTP服务器载入指定url失败图片不能正常显示怎么破...

# -.- coding:utf-8 -.-

'''

Created on 2011-11-19

@author: icejoywoo

'''

import socket

import datetime

# 初始化socket

s = socket.socket()

# 获取主机名, 也可以使用localhost

#host = socket.gethostname()

host = "localhost"

# 默认的http协议端口号

port = 80

# 绑定服务器socket的ip和端口号

s.bind((host, port))

# 服务器名字/版本号

server_name = "MyServerDemo/0.1"

# 缓存时间, 缓存一天

expires = datetime.timedelta(days=1)

# GMT时间格式

GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'

# 相应网页的内容

content = '''

MyServerDemo/0.1

Hello, World!

python.jpg

'''

#f = open("index.html")

#content = f.read()

#print content

# 可同时连接五个客户端

s.listen(5)

# 提示信息

print "You can see a HelloWorld from this server in ur browser, type in", host, "\r\n"

# 服务器循环

while True:

# 等待客户端连接

c, addr = s.accept()

print "Got connection from", addr, "\r\n"

# 显示请求信息

print "--Request Header:"

# 接收浏览器的请求, 不作处理

data = c.recv(1024)

print data

# 获得请求的时间

now = datetime.datetime.utcnow()

# 相应头文件和内容

response = '''HTTP/1.1 200 OK

Server: %s

Date: %s

Expires: %s

Content-Type: text/html;charset=utf8

Content-Length: %s

Connection: keep-alive

%s''' % (

server_name,

now.strftime(GMT_FORMAT),

(now + expires).strftime(GMT_FORMAT),

len(content),

content

)

# 发送回应

c.send(response)

print "--Response:\r\n", response

c.close()

我感觉问题应该是出在content和response上,

其中

content = '''

MyServerDemo/0.1

Hello, World!

python.jpg

'''

response = '''HTTP/1.1 200 OK

Server: %s

Date: %s

Expires: %s

Content-Type: text/html;charset=utf8

Content-Length: %s

Connection: keep-alive

%s''' % (

server_name,

now.strftime(GMT_FORMAT),

(now + expires).strftime(GMT_FORMAT),

len(content),

content

)

用firebug调试时,显示结果是载入指定url失败,但python.jpg跟这个.py文件在同一目录下,怎么会无法读取呢?

找到解决方案了,先读取图片,再直接嵌入到HTML中data_uri = open('python.jpg', 'rb').read().encode('base64').replace('\n', '')

content = '''

MyServerDemo/0.1

Hello, World!

'''.format(data_uri)

之前的做法需要两次GET,这种做法只用一次就行了

难道是这个原因?

当然,你需要根据GET请求判断请求的路径,然后查找文件,不存在返回404界面,存在的话,先将他们读取为bytes,然后判断一下content-type(这个必须的,不然客户端肯定不能正常识别),然后先发送头,再发送刚刚得到的bytes,ok~~~

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19435.html

相关文章 Recommend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值