2

我编写了以下 HTTP 服务器:

import processing.net.*;
import java.io.FileInputStream;
import javax.activation.MimetypesFileTypeMap;


Client client = null;
Server server = null;
MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();

void setup()
{
  server = new Server(this, 80);
  println(1);

  size(700, 700);

  fill(0);
  mimeMap.addMimeTypes("application/bmp bmp BMP Bmp");
}


void draw()
{
  background(255);

  while ( (client = server.available ()) == null) {
  }
  println(2);
  String req = "";
  String fileN;
  byte[] fileC;
  while (client.available () != 0) {
    req += client.readString();
    try { 
      Thread.sleep(100);
    } 
    catch (Throwable t) {
    }
  }

  println(req);
  fileN = URLDecoder.decode(req.split(" ")[1].substring(1));
  if (!fileN.equals("")) {
    try
    {
      FileInputStream fileS = new FileInputStream("C:\\" + fileN);
      fileC = new byte[fileS.available()];
      fileS.read(fileC);

      server.write(
       concatSB(
        "HTTP/1.0 200 OK\r\nContent-Type: " + 
        mimeMap.getContentType(fileN.substring( fileN.lastIndexOf("/") + 1 )) + 
        "\r\nContent-Length: " + 
        fileC.length + 
        "\r\n\r\n", 
        fileC
       )
      );

      println(3);
      println(fileN);
    }
    catch (Exception e)
    {
      server.write("HTTP/1.0 404 Not Found\r\n".getBytes());
      println(fileN + ": " + e.toString());
    }
  }
  exit();
}

void mouseClicked()
{
  server.stop();
  exit();
}

private byte[] concatSB(final String strng, final byte[] bytes) {     
  final StringBuilder sb = new StringBuilder(strng);
  for (byte b : bytes) {         
    sb.append((char)b);
  }
  println(strng);
  return sb.toString().getBytes();
} 

它适用于文本,但是当我发送此 BMP 时:

图形

我得到了这个 BMP,它在 Paint 中自动打开:

损坏的图形

当我在 Paint 中将原始图像转换为 GIF 时,结果无法通过服务器读取,在 IE 中,我得到了错误的图像图标(红色 X);

我怎样才能解决这个问题?

4

1 回答 1

2

我认为通过 StringBuilder 传递二进制文件 C 不是一个好主意。我宁愿做这样的事情:

  server.write(
    "HTTP/1.0 200 OK\r\nContent-Type: " + 
    mimeMap.getContentType(fileN.substring( fileN.lastIndexOf("/") + 1 )) + 
    "\r\nContent-Length: " + 
    fileC.length + 
    "\r\n\r\n"
   );
  server.write(
    fileC
   );
于 2012-09-12T17:29:49.413 回答