【发布时间】:2014-11-22 23:30:36
【问题描述】:
我正在尝试创建一个简单的 http 服务器,但是当我发送 png 文件时,firefox 告诉我图像存在问题。 (图片无法显示)。
我将内容类型更改为八进制流,以便我可以从浏览器下载文件。 通过使用文本编辑器比较原始图像和下载的图像,我意识到下载的图像在开始时遗漏了一些行。
# Provides TCPServer and TCPSocket classes
require 'socket'
server = TCPServer.new('localhost', 1234)
ary = Array.new
f = File.binread '/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
loop do
socket = server.accept
request = socket.gets
index1 = request.index(' ');
index2 = request.index(' ',index1+1);
index3 = request.index("\r\n");
index4 = request.length;
method = request[0,index1]
URI = request[index1+1,index2-index1-1]
version = request[index2+1,index3-index2-1]
CRLF = b2s((request[index3,2] == "\r\n"))
if (URI == "/Shrek" || URI == "/index.html")
socket.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: image/png\r\n" +
"Connection: close\r\n\r\n"
ary = Array.new
f = File.binread '/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
#if I print 'f' here to the console i get the hole image, but downloaded from the browser
#the upper part ist cut
puts f
ary.push(f)
socket.write(ary) # <- update, forgot to copy this line
end
socket.close
end
【问题讨论】:
-
也许我错过了 - 对套接字的写入在哪里?
-
HTTP 标头以空行结束。尝试在
"Content-Type: image/png\r\n"之后添加第二个\r\n -
你说得对,我加了一个\r\n。还添加了 socket.write,我忘记复制了 ;)
标签: ruby image http tcp content-type