使用Java通过HTTP进行图像传输

时间:2012-03-03 19:50:35

标签: java serialization

希望stackoverflow中的Java专家可以解释一下:

我们通过序列化图像成功发送图像(在将其转换为Java ImageIcon Serializable类型之后),但序列化IO看起来很昂贵(readObject(),writeObject()),因为我们一直在点击“java.lang.OutOfMemoryError” :Java堆空间“servlet容器中的错误。

有没有更好的方法通过HTTP传输图像文件?

应用程序正在使用Java Robot类通过servlet连续向多个客户端发送桌面映像(以便于HTTP传输)。 听起来好听的建议,让我发布一些代码,让你了解我的项目。 我必须使用Java(通过使用servlet的网络),我的工作取决于这个工作......请帮助......

__ 从组件中添加重要的代码摘录 __ _ __ _ __ _ __

予。 ClientApplet (捕获桌面图像(通过套接字将序列化发送到中央ImageBroker)

- > II。 ImageBroker (通过套接字读取ClientApplet中的序列化图像 将它发送到servlet以使其可供HTTP查看器小程序使用)

- > III。 ViewerServlet 通过HTTP将图像转发到applet

- > IV.Applet阅读序列化图像

// I. Client Applet
// (sends serialized desktop images to ImageBroker server over TCP sockets )

class ScreenShoot extends Thread {

Socket socket = null;
Robot robot = null; // Used to capture screen
Rectangle rectangle = null; //Used to represent screen dimensions
boolean continueLoop = true; //Used to exit the program

public ScreenShoot(Socket socket, Robot robot, Rectangle rect) {
    this.socket = socket;
    this.robot = robot;
    rectangle = rect;
    start();
}

public void run() {
    ObjectOutputStream oos = null; //Used to write an object to the streem
    try {
        //Prepare ObjectOutputStream
        oos = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String Userid = "test";
    String ConfId = "ONE";

    MyClass sendHeader = new MyClass(Userid,ConfId, 300, 300, 20, 30);
    System.out.println("sendHeader: " + sendHeader);

// Send the header (username, ConferenceID) first before sending the images
    try {
        oos.writeObject(sendHeader);
        System.out.println("sent HEADER object1: ");
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    int countRec = 1;
    while (continueLoop) {
        //Capture screen
        BufferedImage image = robot.createScreenCapture(rectangle);
        /* I have to wrap BufferedImage with ImageIcon because BufferedImage class
         * does not implement Serializable interface
         */
        ImageIcon imageIcon = new ImageIcon(image);

        //Send captured screen to the server

        try {
            System.out.println("ScreenSpyer:before sending image-writeObject");
        //     oos.writeObject(imageIcon);
            oos.writeUnshared(imageIcon);
            countRec++;
            if (countRec > 20 ) {
             oos.reset(); //Clear ObjectOutputStream cache
             countRec = 1;
            }
            System.out.println("ScreenSpyer: New screenshot sent");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        //wait for 1000ms to redu/ e network traffic
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

II.Central ImageBroker Server 代理处理来自各种发件人的图像并将其传送给正确的查看者(通过servlet传送) - 通过TCP套接字从客户端screensender applet接收图像 - 将序列化图像转发到ViewerServlet

// Section READING the incoming images ( this is over simple TCP Sockets)
class HandleSenders extends Thread {
  private Socket socket = null;
  private WinTest mainprog;
  private MessageBin source;
  private InputStream fromServer = null; 

  public HandleSenders(WinTest mainprog, Socket socket, MessageBin source) {
    super("HandleSenders");
    this.socket = socket;
    this.mainprog = mainprog;
this.source = source;

  }

 // getNextMessage() returns the next new message.
 // It blocks until there is one.

 public String getNextMessage() {
  // Create a message sink to wait for a new message from the
  // message source.
  return new MessageHold().getNextMessage(source);
 }

public void run() {
    // Reading Images from SnreenSender client 
    ObjectInputStream in = null;

byte[] buffer = new byte[256];
int fromServer_val, backup_val =0 ;

    try {
        // in = new ObjectInputStream(socket.getInputStream());
        fromServer = socket.getInputStream();    
    in = new  ObjectInputStream(fromServer);
    boolean forever = true;
        int cntr = 1;
        boolean contin = true;
        int counter = 1;

        boolean Found = false;
    String theMessage = "";
    while (contin) {
            // if (cntr++ > 5) break;
            // fromServer_val = fromServer.read(buffer);
            // dealing with null values which crashes the system,
            // if for some problem in transmission you get a null, we just put the 
            // previous valid data
            // into the null one.


     ImageIcon imageIcon = (ImageIcon)in.readObject();

     Found = mainprog.FindViewersAndSend(senderHeader.confid, imageIcon);



    // Blocks first time and only if the structure has no 
            // clients for this sender

            if (!Found)
            theMessage = getNextMessage(); //blocks

部分处理将图像发送到servlet

 public boolean FindViewersAndSend(String confid, ImageIcon imageIcon) {
Iterator it = socketMap.entrySet().iterator();
ObjectOutputStream viewerOut = null;
byte[] buffer = new byte[256];
Socket viewerClient = null;
OutputStream toClient = null;
boolean Found = false;
int recordCount = 1;
try {
   while (it.hasNext()) {
       // Iterating through structures of Viewer servlet socket connections 
       Map.Entry pairs = (Map.Entry)it.next();
   socketUserStruct = getSocketDetails((String)pairs.getKey());
   if ( socketUserStruct != null && !socketUserStruct.equals ("")) {
    StructConfId = (String)socketUserStruct.getConfId();
    StructUserId = (String)pairs.getKey();
       }
   if (StructConfId.equals(confid)) {
          Found = true;
          viewerOut = (ObjectOutputStream)socketUserStruct.getObjectOutputStream();
          // write the serialized data to the servlet....
          // which in turn sends it to the applet over http
          // viewerOut.writeObject(imageIcon);

          viewerOut.writeUnshared(imageIcon);

          recordCount++;   
          if (recordCount > 10) {
                 viewerOut.flush();
                 recordCount = 0;
          }
   }    
    }
} 
catch (IOException e) 
{      /// clean up
        removeSocketClient(StructUserId);

 }
return Found;

}


III。 ViewerServlet - 从Image Broker获取图像并将Serialized图像发送到Applets(通过http)

public void doGet(HttpServletRequest req,
                  HttpServletResponse res) throws ServletException,

    Socket echoSocket = null;
    PrintWriter out = null;
    InputStream fromServer = null;
    byte[] buffer = new byte[256];
    int fromServer_val, backup_val = 0;

    // OutputStream toClient = res.getOutputStream();
    try {
        echoSocket = new Socket("localhost", RES_PORT);
        out = new PrintWriter(echoSocket.getOutputStream(), true);

        String screensize = "300";
        String viewerHeader = userid+","+confid+","+screensize;  
        out.println(viewerHeader);

        out.println("bye");
        out.flush();
      InputStream is = echoSocket.getInputStream();
      ObjectInputStream in = new ObjectInputStream(is);
      ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());


        try {
           int recordCount = 1;
            while (true) {

              ImageIcon imageIcon = (ImageIcon)in.readObject();
              oos.writeObject(imageIcon); 
                if (recordCount++ > 5) {
                    recordCount = 1;
                    oos.flush();
                }
                // oos.flush();


            }
        } catch (ClassNotFoundException e) {
                   .......                   
        } catch (IOException ex) {
            ex.printStackTrace();


        }




    } catch (IOException e) { // show("plainViewAdapter-doGet:4");
        fromServer.close();
    }

}

IV。 Viewer Applet(连接到Viewer Servlet以接收图像)

public void start() {
    try {

        String url_string =
            "http://" + winsellahost + ":" + winsellaport + "/BrowserShare  
             /viewerproxyservlet" +
            "?userid=viewer1&confid=ONE";
        URL url = new URL(url_string);
        InputStream is = url.openConnection().getInputStream();
        ObjectInputStream in = new ObjectInputStream(is);
        boolean firstTime = true;

        while (continueLoop) {

          show("5");
            //Recve client screenshot and resize it to the current panel size

            ImageIcon imageIcon = (ImageIcon)in.readObject();
            // in.reset();
            Image image = imageIcon.getImage();
            image =
                    image.getScaledInstance(cPanel.getWidth(), cPanel.getHeight(),
                                            Image.SCALE_FAST);
            //Draw the received screenshot


        }
        in.close();
        is.close();

    } catch (IOException ex) {
        ex.printStackTrace();

    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }


}

1 个答案:

答案 0 :(得分:1)

不要序列化为对象。

PNG 图像OutputStream中序列化Bufferedimage,并从InputStream中读取另一端

使用ImageIO.write对其进行序列化,使用ImageIO.read对其进行反序列化。

http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html

安东尼