devxlogo

How to Speed Up Data Transfer Between Servlet and Applet

How to Speed Up Data Transfer Between Servlet and Applet

We can speed up the data transfer between servlet and applet in a Web application by compressing the data transferred between them. The example below demonstrates how this is done:

Servlet Code:

 public void doGet(HttpServletRequest req, HttpServletResponse res)              throws ServletException, IOException   {     try      {	res.setHeader("Content-Encoding","gzip");	OutputStream out = res.getOutputStream();	GZIPOutputStream gz = new GZIPOutputStream(out);	String data = "Compressed Data";        gz.write(data.getBytes());	gz.close();       	out.close();      }     catch(Exception e)      {	System.out.println("In CompressServlet: Exception in doGet");      }  }//Applet Code:

 public class UnCompressApplet extends Applet {   String fromServ = "";   public void start()	{	  try	   {	     readData();	   }	  catch(Exception e)	   {	     System.out.println("Exception in start()");	   }	}	public void paint(Graphics g)	 {	    // Display the obtained data  	g.drawString("Contents of Servlet Data: " + fromServ, 10, 10);	 }public void readData() throws Exception  {  try   {      GZIPInputStream gz = new GZIPInputStream( getData() );      byte[] buf = new byte[1024];      int len;      while ((len = gz.read(buf)) > 0)	 fromServ = new String(buf);      gz.close();   }  catch (IOException e)   {      System.out.println("In UncompressApplet: Exception in readData()");   }}public InputStream getData() throws Exception  {try{	//URL of the Web ServerString url = "http://localhost:8080/examples/servlet/CompressServlet";	URL postURL = new URL( url );	URLConnection urlCon = null;	urlCon = postURL.openConnection();	urlCon.setDoOutput(true);	urlCon.setDoInput(true);	return urlCon.getInputStream();}    catch(Exception e)  	{	  e.printStackTrace();	  return null; //something went wrong    }  }//end of getData}//end of classHTML Code :Applet/Servlet Communication

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist