【问题标题】:Ruby How to send image over tcp (http) server to clientRuby如何通过tcp(http)服务器将图像发送到客户端
【发布时间】: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


【解决方案1】:

我现在用上面的代码得到了整个图像,但是我的字符被转义了。

原图以:开头的:

�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

【讨论】:

    【解决方案2】:

    我自己解决了这个问题。最后要添加的是编码(见下文)

     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"
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多