[英]Image transmission over HTTP with Java
Hope the Java experts in stackoverflow can shed some light : 希望Stackoverflow中的Java专家可以阐明一些观点:
We are successfully sending images by serializing the image ( after casting it to Java ImageIcon Serializable type), but the Serialized IO seems expensive ( readObject(), writeObject()), as we keep hitting the "java.lang.OutOfMemoryError: Java heap space" errors in the servlet container. 我们已经通过序列化图像成功地发送了图像(将其转换为Java ImageIcon Serializable类型之后),但是序列化的IO似乎很昂贵(readObject(),writeObject()),因为我们不断遇到“ java.lang.OutOfMemoryError:Java堆” servlet容器中出现“空格”错误。
Is there a better way of transmitting image files in Java over HTTP ? 是否有更好的方法通过HTTP在Java中传输图像文件?
The application is using Java Robot class to send desktop images continually to multiple clients over a servlet ( to facilitate the HTTP transmission). 该应用程序使用Java Robot类通过servlet将桌面图像连续发送到多个客户端(以促进HTTP传输)。 Sounds like good advice already, let me post some of the code to give you an idea for my project.
听起来已经是很好的建议,让我发布一些代码,为您的项目做个主意。 I have to use Java ( over the web that is using servlets), and my job depends on this working out ...please help ...
我必须使用Java(在使用servlet的Web上),而我的工作取决于此工作……请帮助...
__ Adding critical code excerpts from the components __ 从组件中添加关键代码节选 __ _ __ _ __ _ __
__ _ __ _ __ _ __
I. ClientApplet (Captures desktop images(sends serialized over sockets to a central ImageBroker) I. ClientApplet(捕获桌面图像(通过套接字序列化发送到中央ImageBroker)
-> II. -> II。 ImageBroker (Reads Serialized images from ClientApplet over sockets and sends it to servlet to make it available to HTTP viewer applets)
ImageBroker(通过套接字从ClientApplet读取序列化的图像,并将其发送到servlet,以使其可用于HTTP查看器小程序)
-> III. -> III。 ViewerServlet Forward the images to applets over HTTP
ViewerServlet通过HTTP将图像转发到applet
-> IV.Applet reading serialized images -> 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 Broker handles images from various senders and traffics them to the right viewers ( coming through a servlet) -Receives images from client screensender applet over TCP sockets - Forwards Serialized images to ViewerServlet II.Central ImageBroker Server Broker处理来自不同发件人的图像并将其传输到正确的查看器(通过Servlet)-通过TCP套接字从客户端屏幕发送器小程序接收图像-将序列化的图像转发到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
Section handling SENDING the images to servlets 将图像发送到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 - Getting images from Image broker and sends the Serialized image to Applets ( over http)
ViewerServlet-从图像代理获取图像并将序列化的图像发送到Applet(通过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. IV。 Viewer Applet ( Connecting to the Viewer Servlet to receive the images )
查看器小程序(连接到查看器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();
}
}
Don't serialize to an Object. 不要序列化为对象。
Serialize the Bufferedimage in a PNG image OutputStream and read it back on the other side from an InputStream 在PNG图像OutputStream中序列化Bufferedimage,然后从InputStream的另一面读回
Use ImageIO.write to serialize it and ImageIO.read to deserialize it. 使用ImageIO.write对其进行序列化,并使用ImageIO.read对其进行反序列化。
http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html
Anthony 安东尼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.