Asynchronous applet-servlet communication

Hi all,
I am trying to implement asynchronous applet-servlet communication and need your help. Anything would help(I tried with synchronous applet-servlet communication but doesn't solve my problem).
Thanks,

http://java.sun.com/docs/books/tutorial/networking/index.html
You can open a socket connection. Bother the client and the server
can have separate threads for reading and writing and that you gives you
asynchronous communication. Later, if you think the server is generating
too many threads and not scaling, you can use features of .java.nio to
make it more scalable:
java.nio.channels

Similar Messages

  • Applet/servlet communication for byte transmission

    Hello all !
    I wrote an applet to transfer binary file from web servlet (running under Tomcat 5.5) to a client (it's a signed applet) but I have a problem of interpretation of byte during transmission.
    the code of the servlet is :
            response.setContentType("application/octet-stream");
            ServletOutputStream sos = response.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(
                    "C:\\WINDOWS\\system32\\setup.bmp"));
            byte[] b = new byte[1024];
            int nbRead = 1;
            while (nbRead > 0) {
                nbRead = fis.read(b);
                System.out.println("octets lus = " + nbRead);
                sos.write(b, 0, nbRead-1);
            fis.close();
            sos.close();et le code de l'applet qui appelle cette servlet est :
            URL selicPortal = null;
            try {
                selicPortal = new URL(
                        "http://localhost:8080/AppletTest/servlet/FileManipulation");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            URLConnection selicConnection = null;
            try {
                selicConnection = selicPortal.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            selicConnection.setDoInput(true);
            selicConnection.setDoOutput(true);
            selicConnection.setUseCaches(false);
            selicConnection.setRequestProperty("Content-Type",
                    "application/octet-stream");
            try {
                InputStream in = selicConnection.getInputStream();
                FileOutputStream fos = new FileOutputStream(new File(tempDir
                        + "\\toto.bmp"));
                byte[] b = new byte[1024];
                int nbRead = in.read(b);
                while (nbRead > 0) {
                    fos.write(b);
                in.close();
                fos.close();
             } catch (IOException ioe) {
                ioe.printStackTrace();
            }the file dowloaded is broken. it seems that bytes 01 00 or 00 01 are not correctly process.
    Some ideas to help me please ?

    hi,
    have you solved this issue.. please post me the code since i m also doing the applet/servlet communication and can use your code as reference.
    how to read the content placed in the urlConnection stream in the servlet
    Below is my code in applet
    public void upload(byte[] imageByte)
              URL uploadURL=null;
              try
                   uploadURL=new URL("<url>");
                   URLConnection urlConnection=uploadURL.openConnection();
                   urlConnection.setDoInput(true);
                   urlConnection.setDoOutput(true);
                   urlConnection.setUseCaches(false);
                   urlConnection.setRequestProperty("Content-type","application/octet-stream");
                   urlConnection.setRequestProperty("Content-length",""+imageByte.length);
                   OutputStream outStream=urlConnection.getOutputStream();
                   outStream.write(imageByte);
                   outStream.close();
              catch(MalformedURLException ex)
              catch(IOException ex)
    How can i read the byte sent on the outstream (in above code) in the servlet.
    Thanks,
    Mclaren

  • Is there a good advanced review on applet-servlet communication

    I am working on a web application and unfortunately experiencing a lot of trouble trying to use an applet as front end which interacts with a couple of servlets running on Tomcat. I need to get data from one servlet and send data to another.
    There is a lot of messages posted in this and other forums about how to do this, but none of them got a response pointing to a useful advanced reference on this subject. I have reviewed some of the references given, but couldn't find a thorough detailed advanced reference on applet-servlet communication. For this I mean an exhaustive explanation of the mechanism of communication and when and when is neccesary to use each of the multiple configuration possibilities regarding content-type, message-length, request-method, connection settings, and so on.
    Would anybody be so kind to show me the right direction? As I read the (literally) hundreds of messages posted on this topic, I see this info as widely useful. Most of the topic tracks ends on void or with painful no-way sentences, and maybe many people is avoiding Java technology on web application because of this problem (development delays can abort a project).

    This sample chapter in Java developers' guide to Servlets and Jsp focuses on Applet-Servlet communication, is a pretty good one, and is free :
    http://www.javaranch.com/bunkhouse/samps/2809ch12.pdf
    As to an exhaustive & complete guide that covers absolutely everything, I may be wrong but I doubt you'll find anything like that...unless there is a book somewhere dedicated to the subject.

  • Applet-servlet communication, object serialization, problem

    hi,
    I encountered a problem with tomcat 5.5. Grazing the whole web i didn't find any solution (some guys are having the same problem but they also got no useful hint up to now). The problem is as follows:
    I try to build an applet-servlet communication using serialized objects. In my test scenario i write a serialized standard java object (e.g. a String object) onto the ObjectOutputStream of the applet/test-application (it doesn't matters wheter to use the first or the latter one for test cases) and the doPost method of the servlet reads the object from the ObjectInputStream. That works fine. But if i use customized objects (which should also work fine) the same code produces an classnotfound exception. When i try to read and cast the object:
    TestMessage e = (TestMessage)objin.readObject();
    java.lang.ClassNotFoundException: TestMessage
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1205)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ...That seems strange to me, because if i instantiate an object of the same customized class (TestMessage) in the servlet code, the webappclassloader doesn't have any problems loading and handling the class and the code works fine!
    The class is located in the web-inf/classes directory of the application. I've already tried to put the class (with and without the package structure) into the common/classes and server/classes directory, but the exception stays the same (I've also tried to build a jar and put it in the appropriate lib directories).
    I've also tried to catch a Throwable object in order to get information on the cause. But i get a "null" value (the docu says, that this will may be caused by an unknown error).
    I've also inspected the log files intensively. But they gave me no hint. Until now I've spend a lot of time on searching and messing around but i always get this classnotfound exception.
    I hope this is the right place to post this problem and i hope that there is anyone out there who can give me some hint on solving this problem.
    Kindly regards,
    Daniel

    hi, thanks for the reply,
    all my classes are in the web-inf/classes of the web-app and have an appropriate package structure. thus the TestMessage class is inside a package.
    i tried some names for the testclass but it didn't matter. the exception stays the same. I also tried to put the jar in the common/lib but the problem stays.
    Well the problem with loaded classes: As i mentioned in the post above i can instantiate an object of TestMessage in the code without any problems (so the classloader of my webapp should know the class!!)
    only when reading from the objectinputstream the classloader doesn't seem to know the class?? maybe theres a parent classloader resposible for that and doesn't know the class?
    strange behaviour...
    p.s. sending the same object from the servlet to the client works well
    regards
    daniel
    Message was edited by:
    theazazel

  • Applet/Servlet communication - StreamCorruptedException

    Hi, I'm having a problem when I try to connect to a servlet. I am using applet/servlet communication. The problem only occurs when I have lauched a crystal report via http in a new window.
    After the report is launched if I try to hit my servlet I get the following error:
    java.io.CorruptedStreamException: invalid stream header
    Not all crystal reports I launch cause this behavior but I can see nothing in the url I use to launch the report that is out of place or different than other reports.
    APPLET-SERVLET CONNECTION
    try {
    StringBuffer path = new StringBuffer();
    path.append(ip);
    path.append("servlet/DatabaseServlet?");
    path.append("option=getRecords&query=").append(URLEncoder.encode(query,"UTF-8"));
    URL url = new URL(path.toString());
    URLConnection servletConnection = url.openConnection();
    servletConnection.setUseCaches(false);
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
    rc = (RecordCollection) inputFromServlet.readObject();
    inputFromServlet.close();
    } catch (Exception e) {
    e.printStackTrace();
    SERVLET CODE
    Forwards to doPost
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("session id: " + request.getSession().getId());
    this.doPost(request, response);
    LAUNCHING REPORT FROM APPLET
    try {
    String launchURL = host + directory + report + "?promptOnRefresh=0"+ "&" +
    authentication + "&" + key + "&" + startPeriods + "&" + reportYears + "&" + reportTitle + "&" endPeriods "&" + locations + "&" + reportPeriod + "&" + fiscalWeek + "&" + fiscalYear + "&" +time;
    context.showDocument(new URL(launchURL), "_blank");
    } catch (Exception ex) {
    ex.printStackTrace();
    SAMPLE URL THAT CAUSES PROBLEM
    http://localhost:113/Reports/OpenToBuy_3.class?promptOnRefresh=0&user0=rpuser&password0=er34sw1&[email protected]=rpuser&[email protected]=er34sw1&user0@sub2=rpuser&[email protected]=er34sw1&promptex-key="L","L1","ALL"&promptex-start="1"&promptex-years="2004","2004"&promptex-title="Report Title"&promptex-end="1"&promptex-locs="01","03","04","05"&promptex-period="Feb 2004 [04-01]"&promptex-cw="1"&promptex-cy="2004"&promptex-time=-2-52728"
    Everything works fine until I launch this report then I can no longer get data from my servlet. I thought the URL lenght for the report might be the problem but I lauch a report with a URL longer than the problem one and there I don't get the errors after. When I try to connect to the servlet the println statement in the doGet method of my servlet doesn't get printed so it's not even making it inside that method in the servlet.
    Anyone have any idea what could be causing this? Anyone have any ideas what would be causing this? I'm really stumped.

    I've seen this problem before. Because your accessing a complete URL (ie http://<host>:<port>/xxx), you are actually creating a new session. Whenever the applet opens a connection to a servlet it is running on it's own session not the same as the JSP. This is rather obvious since the Page and Applet are separate entities.
    Try sending authentication with the url. I think the syntax is:
    username:password@http://localhost/xxx
    However I'm not sure how well this might work for Tomcat. As for Java it may try and throw a MalformedURLException I would have to test it first - it's been a long time since I used this technique!
    Wish I could be more help,
    Anthony

  • Problem in Applet Servlet communication in cluster

              Our new production server has been configured with
              clusters very recently.The application is running fine if and only if one instance
              of weblogic is running.The application has two applets that communicate through a
              servlet and the servlet is hosted by both the WL servers in the cluster.
              Please consider the following scenario :
              1. JSP#1(having embedded tag for Applet#1) is served by, say, WLInstance#1.
              2. JSP#2(having embedded tag for Applet#2) is served by, say, WLInstance#2.
              3. Applet#1 is loaded by BrowserInstance#1.
              4. Applet#2 is loaded by BrowserInstance#2.
              The way I understand applet-servlet communication is as follows :
              The servlets are invoked through the url-pattern specified in web.xml - if the applet
              is making use of a certain url-pattern that is mapped to servlet, then the call from
              that applet will
              eventually invoke a servlet on any of the two instances till a session is established,
              at which point all subsequent requests from the same browser window/frame will go
              to the servlet hosted on the instance where the http session was created.
              (Please correct me, if I am wrong.)
              So, Applet#1 will always talk to the servlet hosted by WLInstance#1 and Applet#2
              will always talk to the servlet hosted by WLInstance#2.
              In our case, the servlet is maintaining data structures to store all the messages
              sent by diffterent instances of Applets.
              The applets periodically polls the messages from those data structures.Once the messages
              are polled, those are deleted from
              the data structures.
              As there are two different instances of the servlet, Applet#1 never gets messages
              posted by Applet#2.
              Is there a way to make this data structure global to both the servlet instances?
              Thanks and best regards,
              Subir Das
              

              "Subir Das" <[email protected]> wrote:
              >So, Applet#1 will always talk to the servlet hosted by WLInstance#1 and
              >Applet#2
              >will always talk to the servlet hosted by WLInstance#2.
              This statement is not entirely true.
              Suppose WLInstance#1 were to be brought down (for whatever reason), Applet#1 will
              then talk to servlet hosted by WLInstance#2.
              Server pinning could be modified by different load balancing algorithms, configurable
              via containers (or hardware).
              So don't count on which servlet instance your applet is going to be served by.
              Instead consider to give a second look into the design of the servlet data structure
              (object):
              1.Read from data store, if it has been persisted.
              2.If the data is client related then consider sticking the data into session, which
              would then replicate to other WL instances.
              3.Stateless EJB in a cluster ? Don' know much about this(yet).
              My 2 cents..Good luck.
              Rama
              

  • Big Problem in Applet-Servlet Communication-(Help)

    I wrote an method to send serialized objects from Applet to Servlet,
    the method is as following:
    private ObjectInputStream postObjects (URL servlet, Serializable objs[], String sessionID) throws Exception {
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    try{
    URLConnection con = servlet.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type","application/x-java-serialized-object");
    con.setAllowUserInteraction(false);
    con.setRequestProperty("Cookie", sessionID);
    out = new ObjectOutputStream(con.getOutputStream());
    int numObjects = objs.length;
    for(int x = 0; x < numObjects; x++){
    out.writeObject(objs[x]);
    out.flush();
    out.close();
    in = new ObjectInputStream(con.getInputStream());
    }catch(Exception e){
    e.printStackTrace(System.err);
    throw e;
    }finally{
    return in;
    when I call this method, I got the following error message in Applet console,
    my platform is Salaris 5.8 + iPlanet 6.0.
    java.io.EOFException
         at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2150)
         at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2619)
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:726)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:251)
         at com.shinewave.lms.core.client.ServletProxy.postObjects(ServletProxy.java:255)
         at com.shinewave.lms.core.client.ServletProxy.doInitialize(ServletProxy.java:76)
         at com.shinewave.lms.core.client.APIAdapterApplet.LMSInitialize(APIAdapterApplet.java:60)
    java.lang.NullPointerException
         at com.shinewave.lms.core.client.ServletProxy.doInitialize(ServletProxy.java:77)
         at com.shinewave.lms.core.client.APIAdapterApplet.LMSInitialize(APIAdapterApplet.java:60)
    java.lang.NullPointerException
         at com.shinewave.lms.core.client.ServletProxy.doInitialize(ServletProxy.java:82)
         at com.shinewave.lms.core.client.APIAdapterApplet.LMSInitialize(APIAdapterApplet.java:60)
    Please help me to solve this problem, thank you very much.

    Hi..
    Sorry abt this. But I was hoping if u could help out on this..
    I am trying to implement a applet to servlet communication...
    wherin the servlet would read data from the database... and send it back to the applet which gets displayed on the applet...
    But the problem is that the applet is not able to establish a connection with the servlet..
    I am also using another supportive class whose object is basically passed from the servlet to the applet..
    could u help me..
    below is the piece of code...
    APPLET:
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class TestApplet extends JApplet implements ActionListener
         JButton btnLoad;
         JTextField tfEmpno, tfFname, tfLname, tfSalary;
         URL url;
    private String webServerStr = null;
    private String hostName = "sandy";
    private int port = 8085;
    private String servletPath = "/jdbcTest.DBDetailsServlet";     
    public TestApplet()
         super();
    // suppress Warning Message
    getRootPane().putClientProperty"defeatSystemEventQueueCheck",Boolean.TRUE);
         public void actionPerformed(ActionEvent ae)
              if(btnLoad.getText().equals("Load"))
                   if(loadData())
                        btnLoad.setText("Save");
              else
                   btnLoad.setText("Load");
    //               saveData();
         public void init()
              setBackground(Color.pink);
              tfEmpno = new JTextField(10);
              tfFname = new JTextField(10);
              tfLname = new JTextField(10);
              tfSalary= new JTextField(10);
              JPanel panel = new JPanel();
              panel.setLayout(new FlowLayout());
              panel.add(tfEmpno);
              panel.add(tfFname);
              panel.add(tfLname);
              panel.add(tfSalary);
              getContentPane().add(panel, BorderLayout.CENTER);
              JPanel bottom = new JPanel(new FlowLayout());
              btnLoad = new JButton("Load");
              btnLoad.addActionListener(this);
              bottom.add(btnLoad);
              getContentPane().add(bottom, BorderLayout.SOUTH);
         public boolean loadData()
              try
         System.out.println("Web Server host name: " + hostName);
         webServerStr = "http://" + hostName + ":" + port + servletPath;
         System.out.println("Web String full = " + webServerStr);
                   String servletGET = webServerStr + "?"
         + URLEncoder.encode("UserOption") + "="
         + URLEncoder.encode("AppletDisplay");     
    //               url = new URL(getCodeBase(),"http://sandy:8080/servlet/jdbcTest.DBDetailsServlet");
                   System.out.println("Complete Servlet Url => " + servletGET);
                   url = new URL(servletGET);
                   URLConnection con = url.openConnection();
                   con.setUseCaches(false); // Turn off caching.
                   InputStream in = con.getInputStream();
                   System.out.println("\nsuccess ....... con.getInputStream() ");
                   ObjectInputStream ois = new ObjectInputStream(in);
                   System.out.println("\nsuccess ....... new ObjectInputStream(in) ");
                   Object object = ois.readObject();
                   System.out.println("\nGot the object from servlet...");
                   if(object != null)
                        System.out.println("\nObject NOT null ...");
                        ArrayList result = (ArrayList) object;
                        jdbcTest.EmployeeValue empval = (jdbcTest.EmployeeValue) result.get(0);
                        tfEmpno.setText(""+empval.getEmp_no());
                        tfFname.setText(empval.getFname());
                        tfLname.setText(empval.getLname());
                        tfSalary.setText(""+empval.getSalary());
                        System.out.println("\nObject processed " + result);
                        repaint();
                   return true;
              catch(Exception e)
                   e.printStackTrace();
                   System.out.println("\n\n loadData()=> E X C E P T I O N : " + e + "\n");
                   return false;               
         public void saveData()
              //yet to be implemented..
    SERVLEt:
    package jdbcTest;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DBDetailsServlet extends HttpServlet
         public void doGet(HttpServletRequest req,HttpServletResponse res )throws ServletException, IOException
              System.out.println("\nInside the doGet()\n");
              ArrayList results = getDetails();
              ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());
              oos.writeObject(results);
         public void doPost(HttpServletRequest req,HttpServletResponse res )throws ServletException, IOException
              System.out.println("\nInside the doPost()\n");
              doGet(req,res);
         public ArrayList getDetails()
              try
                   System.out.println("\nServlet : inside GetDetails...");
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   java.sql.Connection con = java.sql.DriverManager.getConnection("jdbc:odbc:SandyDSN","","");
                   java.sql.Statement stmt = con.createStatement();
                   System.out.println("\n Statement created..");
                   java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM EMP WHERE EMP_NO = 222");
                   System.out.println("\n Query Executed...");
                   ArrayList results = new ArrayList();
                   while(rs.next())
                        EmployeeValue empval = new EmployeeValue();
                        empval.setEmp_no(rs.getLong("EMP_NO"));
                        empval.setFname(rs.getString("FNAME"));
                        empval.setLname(rs.getString("LNAME"));
                        empval.setSalary(rs.getLong("SALARY"));
                        results.add(empval);
                   System.out.println("\n Resultset Obtained...");
                   stmt.close();
                   con.close();
                   return results;
              catch(Exception e)
                   System.out.println("Error while retreiving details....." + e);
                   return null;
         public boolean saveDetails(EmployeeValue empval)
              try
                   return true;
              catch(Exception e)
                   System.out.println("Error while updating details....." + e);
                   return false;
    The utility class EMployeeValue is as below:
    package jdbcTest;
    import java.io.*;
    class EmployeeValue implements Serializable
         private long emp_no;
         private String fname;
         private String lname;
         private long salary;
         public EmployeeValue()
              super();
         public EmployeeValue(long eno, String fn, String ln,long sal)
              super();
              setEmp_no(eno);
              setFname(fn);
              setLname(ln);
              setSalary(sal);
         public long getEmp_no()
              return emp_no;
         public java.lang.String getFname()
              return fname;
         public java.lang.String getLname()
              return lname;
         public long getSalary()
              return salary;
         public void setEmp_no(long newEmp_no)
              emp_no = newEmp_no;
         public void setFname(java.lang.String newFname)
              fname = newFname;
         public void setLname(java.lang.String newLname)
              lname = newLname;
         public void setSalary(long newSalary)
              salary = newSalary;

  • Need help with applet servlet communication .. not able to get OutputStream

    i am facing problem with applet and servlet communication. i need to send few image files from my applet to the servlet to save those images in DB.
    i need help with sending image data to my servlet.
    below is my sample program which i am trying.
    java source code which i am using in my applet ..
    public class Test {
        public static void main(String argv[]) {
            try {
                    URL serverURL = new URL("http://localhost:8084/uploadApp/TestServlet");
                    URLConnection connection = serverURL.openConnection();
                    Intermediate value=new Intermediate();
                    value.setUserId("user123");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setDefaultUseCaches(false);
                    // Specify the content type that we will send binary data
                    connection.setRequestProperty ("Content-Type", "application/octet-stream");
                    ObjectOutputStream outputStream = new ObjectOutputStream(connection.getOutputStream());
                    outputStream.writeObject(value);
                    outputStream.flush();
                    outputStream.close();
                } catch (MalformedURLException ex) {
                    System.out.println(ex.getMessage());
                }  catch (IOException ex) {
                        System.out.println(ex.getMessage());
    }servlet code here ..
    public class TestServlet extends HttpServlet {
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             System.out.println(" in servlet -----------");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ObjectInputStream inputFromApplet = null;
            Intermediate aStudent = null;
            BufferedReader inTest = null;
            try {         
                // get an input stream from the applet
                inputFromApplet = new ObjectInputStream(request.getInputStream());
                // read the serialized object data from applet
                data = (Intermediate) inputFromApplet.readObject();
                System.out.println("userid in servlet -----------"+ data.getUserId());
                inputFromApplet.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("WARNING! filename.path JNDI not found");
            } finally {
                out.close();
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in foGet -----------");
            processRequest(request, response);
         * Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in doPost -----------");
            processRequest(request, response);
         * Returns a short description of the servlet.
         * @return a String containing servlet description
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    }the Intermediate class ..
    import java.io.Serializable;
    public class Intermediate implements Serializable{
    String userId;
        public String getUserId() {
            return userId;
        public void setUserId(String userId) {
            this.userId = userId;
    }

    Hi,
    well i am not able to get any value from connection.getOutputStream() and i doubt my applet is not able to hit the servlet. could you review my code and tell me if it has some bug somewhere. and more over i want to know how to send multiple file data from applet to servlet . i want some sample or example if possible.
    do share if you have any experience of this sort..
    Thanks.

  • Applet Servlet communication compiles but does not communicate

    Hi,
    I have a applet which has a button named A. By clicking the button, the applet passes the letter A to the servlet. The servlet in turn accesses an Oracle database and retrieves the name corresponding to letter A from a table (name is Andy in the present case). The servlet interacts with the databse via a simple stored procedure and uses its output parameter to display the name Andy back in the applet.
    Both the applet and servlet codes have compiled fine(servlet code compiled with -classpath option to servlet jar using a TOMCAT). However, on clicking button A in the applet, I do not get the name Andy.
    Any help/suggestion in resolution of this is highly appreciated. Thanks in advance.
    HTML CODE:
    <html>
    <center>
    <applet code = "NameApplet.class" width = "600" height = "400">
    </applet>
    </center>
    </html>
    STORED PROCEDURE CODE:
    procedure get_letter_description(
    ac_letter IN CHAR,
    as_letter_description OUT VARCHAR2) IS
    BEGIN
    SELECT letter_description INTO as_letter_description FROM letter WHERE letter =
    ac_letter;
    EXCEPTION
    WHEN no_data_found THEN as_letter_description := 'No description available';
    END get_letter_description;
    APPLET CODE:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class NameApplet extends Applet implements ActionListener
    private TextField text;
    private Button button1;
    private String webServerStr = null;
    private String hostName = "localhost";
         private int port = 8080;
    private String servletPath = "/examples/servlet/NameServlet?letter=";
    private String letter;
    public void init()
         button1 = new Button("A");
    button1.addActionListener(this);
    add(button1);
              text = new TextField(20);
         add(text);
    // get the host name and port of the applet's web server
              URL hostURL = getCodeBase();
         hostName = hostURL.getHost();
    port = hostURL.getPort();
              webServerStr = "http://" + hostName + ":" + port + servletPath;
    public void actionPerformed(ActionEvent e)
         if (e.getSource() == button1)
         letter = "" + 'A';
    private String getName(String letter){
    String name = "" ;
    try {
              URL u = new URL(webServerStr + letter);
              Object content = u.getContent();
    name = content.toString();
         } catch (Exception e) {
         System.err.println("Error in getting name");
    return name;
    SERVLET CODE:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import java.util.Properties;
    public class NameAppletServlet extends HttpServlet {
    private static Connection conn = null;
    private static final char DEFAULT_CHAR = 'A';
    private static final char MIN_CHAR = 'A';
    private static final char MAX_CHAR = 'G';
    private static final String PROCEDURE_CALL
    = "{call get_letter_description(?, ?)}";
    protected void doGet( HttpServletRequest request,
    HttpServletResponse response )
    throws ServletException, IOException
    handleHttpRequest(request, response);
    protected void doPost( HttpServletRequest request,
    HttpServletResponse response )
    throws ServletException, IOException
    handleHttpRequest(request, response);
    protected void handleHttpRequest( HttpServletRequest request,
    HttpServletResponse response )
    throws ServletException, IOException
    String phrase = null;
    char letter = getLetter(request, DEFAULT_CHAR);
    if (letter >= MIN_CHAR && letter <= MAX_CHAR) {
    try {
    name = getName(conn, letter);
    } catch (SQLException se) {
    String msg = "Unable to retrieve name from database.";
    name = msg;
    } else {
    String msg = "Invalid letter '" + letter + "' requested.";
    //throw new ServletException(msg);
    phrase = msg;
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.println(name);
    private String getName(Connection conn, char letter)
    throws SQLException
    CallableStatement cstmt = conn.prepareCall(PROCEDURE_CALL);
    cstmt.setString(1, String.valueOf(letter));
    cstmt.registerOutParameter(2, Types.VARCHAR);
    cstmt.execute();
    String name = cstmt.getString(2);
    cstmt.close();
    return name;
    private char getLetter(HttpServletRequest request, char defaultLetter) {
    char letter = defaultLetter;
    String letterString = request.getParameter("letter");
    if (letterString!=null) {
    letter = letterString.charAt(0);
    return letter;
    public void init(ServletConfig conf) throws ServletException {
    super.init(conf);
    String dbPropertyFile = getInitParameter("db.property.file");
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection(
    "jdbc:oracle:thin:myserver:1521:CDD",
    "scott",
    "tiger");
    } catch (IOException ioe) {
    throw new ServletException(
    "Unable to init ReinforcementServlet: " + ioe.toString());
    } catch (ClassNotFoundException cnfe) {
    throw new ServletException(
    "Unable to init ReinforcementServlet. Could not find driver: "
    + cnfe.toString());
    } catch (SQLException se) {
    throw new ServletException(
    "Unable to init ReinforcementServlet. Error establishing"
    + " database connection: " + se.toString());
    }

    Hi,
    I am not able to understand by which method you are doing Applet-Servlet commuincation.
    If you want to use Object Serialization method, plz.get the details from following URL.
    http://www.j-nine.com/pubs/applet2servlet/
    Ajay

  • EOF exception during applet - servlet communication

    I am developing a system for the US Gov't. This system currently
              utilizes several applets which access corresponding servlets on
              WebLogic. Seemingly, things went wrong for no apparent reason this
              morning. When, trying to run our applets, WebLogic throws an exception:
              "Caught EOFException in the stream header" These exceptions occur
              everytime the servlet would open the input stream from the applet. What
              makes things mind-boggling is that these applets/servlets were working
              this morning, and suddenly now give these exceptions. The code for both
              the applets and servlets has not been touched in weeks. Furthermore, i
              tested even further by running WebLogic locally and running the applets
              in our IDE (as applications) and the same results occur. I am running
              WebLogic 5.1 SP6 on both the remote and local system and am utilizing
              JDK 1.3 on both as well. The server is running on WinNT SP6 and locally
              is Win2000 Pro SP1. These applets are critical to the entire system and
              i am just totally baffled as to why something that was working fine one
              day ago should all of the sudden spit up errors and exceptions.
              If anyone can give me some insight as to what is going on, please let me
              know.
              Thank you,
              Randy Strobel
              [email protected]
              

    Randy,
              I don't know of any particular reasons why WebLogic would suddenly affect an
              application in the manner that you describe. Start by figuring out where
              the message comes from:
              > "Caught EOFException in the stream header"
              I assume that is in WebLogic's code, not yours? Figure out as close as
              possible who is detecting this error condition. If it is in WebLogic's
              code, you can ask support at BEA to tell you what it is complaining about
              (i.e. what it is expecting to read).
              You will have to post the exception trace here and it would help to see the
              code that is causing the exception.
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com
              +1.617.623.5782
              WebLogic Consulting Available
              "Randy Strobel" <[email protected]> wrote in message
              news:[email protected]...
              > I am developing a system for the US Gov't. This system currently
              > utilizes several applets which access corresponding servlets on
              > WebLogic. Seemingly, things went wrong for no apparent reason this
              > morning. When, trying to run our applets, WebLogic throws an exception:
              > "Caught EOFException in the stream header" These exceptions occur
              > everytime the servlet would open the input stream from the applet. What
              > makes things mind-boggling is that these applets/servlets were working
              > this morning, and suddenly now give these exceptions. The code for both
              > the applets and servlets has not been touched in weeks. Furthermore, i
              > tested even further by running WebLogic locally and running the applets
              > in our IDE (as applications) and the same results occur. I am running
              > WebLogic 5.1 SP6 on both the remote and local system and am utilizing
              > JDK 1.3 on both as well. The server is running on WinNT SP6 and locally
              > is Win2000 Pro SP1. These applets are critical to the entire system and
              > i am just totally baffled as to why something that was working fine one
              > day ago should all of the sudden spit up errors and exceptions.
              >
              > If anyone can give me some insight as to what is going on, please let me
              > know.
              > Thank you,
              > Randy Strobel
              > [email protected]
              >
              >
              

  • Netscape problem with applet servlet communication

    Netscape always seems to get in the way when you use applets, right?
    I have a nice set of code from a book that shows how to do applet->servlet stuff.
    But although I'm doing this all in the privacy of my own localhost Netscape immediately put a spanner in the works with a security exception and wouldn't let the servlet respond.
    Anyone know what to do here.
    The answer is to use Internet Explorer, possibly, but I'm in linux, and I can't get Opera to work with java yet.
    Anyone got any ideas? Thanks.

    I encountered a security exception with Netscape in Linux when attempting applet-servlet stuff but that's prpbably because I haven't got the plugin for that yet...in fact I don't know if a plugin is available for sure...let me know if you do. As a matter of fact I plan on using the HTMLConverter this weekend to find out if it'll download a plugin.
    The applet-servlet thing runs fine in IE and Netscape on my Windows box as long as the plugins are there and I use the appropriate plugin tags in the HTML
    Post what you find out,
    Brad

  • Applet Servlet communication (urgent)

    Hi,
    I m using Netscape Enterrpise server 4.0 as my web server. I am passing data from applet to servlet using BufferedInputStream(). But it takes about 30 seconds to send the data. If i don't use it, the data is not being read by the servlet. Is there any alternative to this ? Please help.
    Thanks

    It's only the primary key field that i am passing to the servlet from applet .. For this particular process, it takes 30 seconds + other things like loading the applet, etc. so in all, it takes about 1 minute just to fetch the data from servlet which is not reasonable. We have monitored the whole process. We found that other things like query, etc. does not take much time, but BufferedInputStream() itself takes 30 seconds. Regarding communication line, it is quite fast. We are a corporate sector, so no doubt about the speed of the communication line ...
    Thanks for help.

  • How to Obtain Applet -servlet communication through https protocol

    We are trying to use https protocol.
    First I will explain Our Architecture. We are using JRun 3.0
    as servlet engine. We are using iplanet as a webserver.
    There are two iplanet webservers.
    There is a firewall between two iPlanet servers. i.e, one webserver
    is outside the firewall. JRun is communicating with inside iplannett
    webserver and inside iplannett webserver is communicating with
    outside iplannet server.
    If we are trying to run the application with
    this firewall, our applet is not loading,
    but the servlets and jsp pages are all working fine.
    Without the firewall, everything is working fine.
    The applet is also working fine.
    But, with the firewall, our applet is not loading.
    We are using JRE 1.3 as java plug-in.
    What is the problem so that the applet is not loading.
    and How to resolve this? can anybody give suggestion in this regard?
    Thanks in advance.

    No, I am not getting any security exception for the applet, but I am getting the following exception when working with HTTPS. The same application works fine with the default HTTP protocol
    java.net.UnknownServiceException: Input from HTTPS not expected until OutputStream is closed
         at sun.plugin.protocol.https.BrowserHttpsURLConnection.getInputStream(Unknown Source)
         at JBSchedulerXNew.initReceiveAppointmentData(JBSchedulerXNew.java:122)
         at JBSchedulerXNew.initReceiveAppointmentData(JBSchedulerXNew.java:92)
         at JBSchedulerXNewDemo.init(JBSchedulerXNewDemo.java:110)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)

  • Delays in applet-servlet communication via serialization

    The application that I am developing requires the applet to communicate with a servlet. It works fine except that it seems to send the data in spurts. The servlet seems to wait for good time before it sends out the next batch. It also seems that the batch is defined by the amount of data collected before the final write. This is inspite of flushing data and reseting the stream after every write.
    Please advise what could be done to solve this problem. I have added the detailed description below.
    DESCRIPTION
    APPLET
    The applet opens a ObjectInput Stream (HTTP Tunneling) over the URLConnection and waits for Objects to come to it on a separate thread . I receive the objects and put them in a queue to ensure quick reading from the stream.
    Relevant Code:
    try{
    URL serveletURL = new URL( baseURL + cduURL);
    System.out.println(" URL is " + serveletURL);
    cduCtrlConn = (HttpURLConnection ) serveletURL.openConnection();
    cduCtrlConn.setUseCaches(false);
    cduCtrlConn.setDoInput(true);
    inStream = new ObjectInputStream(
    new BufferedInputStream(cduCtrlConn.getInputStream()));
    catch (Exception ex) {
    ex.printStackTrace();
    try {
    dataQ = new Vector(30);
    DataEventObj tmpDeObj = (DataEventObj) inStream.readObject();
    eObjListener = new EntityObjectListener(dataQ,inStream);
    EntityObjectListener is extends thread and waits on the stream. Once it gets the objects it addes it to the dataQ (vector). It relevant code is .............
    if (NmsClientGlobals.TRACE2)
    System.out.println( "EntityObjectListener.run(): Reading object");
    deObj = (DataEventObj) inStream.readObject();
    SERVLET
    The servlet opens a ObjectOutputStream over the HttpServletResponse. It first gets a bunch of objects from a database and writes to the stream. It also registers for change events coming from the database. When these events comes, it gets the new objects and writes them to Stream.
    Relevant Code:
    response.setStatus (HttpServletResponse.SC_OK);
    outStream = new ObjectOutputStream(
    new BufferedOutputStream(response.getOutputStream(),256));
    outStream.flush();
    // I used different buffer sizes (default-512, 1024, 256) to see if it make a difference .. it seems // not
    .......... // The following the done for all objects available in the database in a loop
    outStream.writeObject(tmpDataEnvObj);
    outStream.flush(); // Doing repeat flush to ensure that it goes through
    outStream.flush();
    outStream.flush();
    outStream.flush();
    outStream.flush();
    outStream.reset(); // reset is suggested to make stream work
    outStream.flush();
    utilLogger.debug("Written object: " + deObj.flag );
    The same code is used by thread that receives notification and then writes it to the stream. If this thread does not receive notifications for 10secs it writes dummy object to the stream. It was done as an attempted fix to the problem (if connection dies ). After adding it, I saw some interesting observations
    SOME OBSERVATIONS
    1. The server logs prints out that the object has been written but the client logs (java console) shows that it is waiting for input to come.
    2. If the amount of data is less then it takes longer for data to come to the client. It seems to me that the server waits for the stream to be filled with dummy data before it sends the final data packet. This seems to be only explaination for this observation is that there is a threshold for packet size. But, I know of no option to set this threshold. Anyway, this is analysus and may not be correct.
    3. I ran a snoop on the connection between the PC and Sun Machine. The queues for the TCP are empty. It seems that after server code prints to the logs that data is written, the TCP doesnot receive it. It seems something in the Java API or the tomcat webserver is holding the data.
    ENVIRONMENT
    server
    Platform: Solaris 2.8
    Java : jre 1.2.2_008
    Web server: Tomcat 3.2.1
    Client
    IE 5.5 with java plugin 1.2.2_008
    I appreciate your help in solving this problem
    -Seonie

    You are using a communication protocol (HTTP) that is designed for "client sends 1 request, server sends 1 response, end of story" pattern for something that is more than that. I understand that you are trying to send binary data over HTTP in order to tunnel over a firewall-friendly protocol, but HTTP was not designed for long-lasting connections. (because HTTP is "client pull", you will have to keep the connection open for a long time and keep the client blocked on read).
    This is not the ideal solution. You have been warned.
    However, if you insist on it and do not want to close the stream, try an HTTP-specific way of flushing data, like
    response.flushBuffer();The motivation behind this suggestion is that the OutputStream you are getting from the response object is probably already buffered, but it likely goes off of a buffer maintained by the HTTP implementation. Hence you can try flushing that directly.
    Vlad.

  • Https applet servlet communication

    Hi friends, is there any way to make a communication between applet and servlet via https?

    URLConnection works fine.
    Now for the fine print...
    If you have an applet running in MSJVM (equivalent to 1.1.X), Netscape JVM (1.1.x) or Sun Java Plugin (until v. 1.3.X), URLConnection simply uses the browser's SSL implementation and SSL works fine if the browser is correctly configured. The trusted CA certificates are the CA certificates in the Internet Explorer trusted CA database (if running in Internet Explorer) or the Netscape trusted CA database (if running in Netscape).
    If your applet runs under Sun Java Plugin 1.4.X (required by Mozilla and Netscape 7, and probably by Internet Explorer running under Windows XP and 2003 - not for technical reasons but by legal ones), the story is different.
    URLConnection uses JSSE (Sun's pure Java SSL implementation), and it uses the Sun Plugin trusted CA database (the file cacerts). The list of CAs is smaller than the list of Internet Explorer or Netscape, and it is not easy to update (requires a manual process). Adding to it, older versions (1.4.0, 1.4.1 and 1.4.2 until 1.4.2_02) simply have problems if you are using a Microsoft proxy that requires NTLM authentication.
    So if you want to use SSL you need to be aware of all that deployment problems.
    a) Use the latest version of the Sun Plug-In you can deploy in your clients (1.4.2_04)
    b) Verify if the web server running HTTPS has a certificate issued by some CA included in the CACERTS list (if you have very few clients, you can try to update CACERTS manually for each client if your CA is not included in the CACERTS file, but probably it is cheaper to get a certificate issued by some CA included in the CACERTS instead.)

Maybe you are looking for

  • Computer freezes in lid-closed mode when connected to external display

    I have a Sylvania SC190 CRT display connected to my Powerbook via a VGA to DVI adapter. Every time I put the computer in lid-closed mode and try to run it off of just the SC190, after a few minutes it freezes up and I have to hard restart it(hold pow

  • How do I check voicemail without my phone ?

    My wife's phone got damaged and she want's to check her cell voicemail from another phone. Is this possible ?   If so, how ? Thanks in advance

  • IPhoto access from iPads

    OK, maybe a simple question, maybe not, but I've been unable to find a clear answer. The queation is easy:  is there a way that I can access my iPhoto library from iPads/iPhones on the same network (MAC is wired).  I'm not looking to edit or store ph

  • Unable to Tag objects

    I have set up the parameters for a custom role to allow Tagging and favourites however neither icon appears in any screen. We can access the community clouds But Cannot tag: is there a specific PFCG setting or something along these lines that is rest

  • Uninstall Database manually for Unicode Conversion

    Hi Guys, While performing a Unicode Conversion, during Export, Unistall and Import of Database, I would like to improve times for Database Creation since its 5TB My goal is to delete SAP/DB Instance Non-Unicode but keeping Tablespaces and Datafiles L