Ruby如何通过tcp(http)服务器向客户端发送图像
我试图创建一个简单的http服务器,但当我发送一个png文件时,firefox告诉我图像有问题。(无法显示图像) 我将内容类型更改为octed stream,以便可以从浏览器下载文件。 通过比较原始图像和下载的图像与文本编辑器,我意识到下载的图像在开始时遗漏了一些行Ruby如何通过tcp(http)服务器向客户端发送图像,ruby,image,http,tcp,content-type,Ruby,Image,Http,Tcp,Content Type,我试图创建一个简单的http服务器,但当我发送一个png文件时,firefox告诉我图像有问题。(无法显示图像) 我将内容类型更改为octed stream,以便可以从浏览器下载文件。 通过比较原始图像和下载的图像与文本编辑器,我意识到下载的图像在开始时遗漏了一些行 # Provides TCPServer and TCPSocket classes require 'socket' server = TCPServer.new('localhost', 1234) ary = Array.
# 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
#提供TCPServer和TCPSocket类
需要“插座”
server=TCPServer.new('localhost',1234)
ary=Array.new
f=File.binread'/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
环道
socket=server.accept
request=socket.get
index1=请求索引(“”);
index2=请求索引(“”,index1+1);
index3=request.index(“\r\n”);
index4=请求长度;
方法=请求[0,index1]
URI=请求[index1+1,index2-index1-1]
版本=请求[index2+1,index3-index2-1]
CRLF=b2s((请求[index3,2]=“\r\n”))
if(URI==“/Shrek”| | URI==“/index.html”)
socket.print“HTTP/1.1 200正常\r\n”+
“内容类型:image/png\r\n”+
“连接:关闭\r\n\r\n”
ary=Array.new
f=File.binread'/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
#如果我在控制台上打印“f”,我会得到孔图像,但是是从浏览器下载的
#上半部分是一个切口
放f
推送(f)
socket.write(ari)#我现在用上面的代码获得了整个图像,但是我的字符被转义了
原始图像以以下内容开头:
�PNG
IHDR�H
�_jsRGB���gAMA���a
[...]
我通过浏览器接收到的图像以
["\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x00\xF3\x00\x00\x01H\b\x02\x00\x00\x00\n\xEE_j\x0
我自己解决了这个问题。最后要添加的是编码(见下文)
也许我没有找到它-写入套接字的位置在哪里?HTTP头以空行终止。尝试在“内容类型:图像/png\r\n”
之后添加第二个\r\n
您说得对,我添加了一个\r\n。还添加了socket.write,我忘了复制它;)
if (URI == "/Shrek")
socket.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: image/png; charset=utf-8\r\n" +
"Connection: close\r\n\r\n"