繁体   English   中英

Ruby如何通过TCP(http)服务器将图像发送到客户端

[英]Ruby How to send image over tcp (http) server to client

我正在尝试创建一个简单的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

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

原始图片以开头:

�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

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

 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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM