Servlet - j2me communication

hi,
i have written a basic servlet and j2me communication project. servlet gets the command, and increase counter value 1 up. from two different mobile phone emulators, i connect to the servlet. when i send a request to the servlet from one emulator, then counter returns 1. From the other emulator, when i send a request, then counter returns 2. do the two different emulators use the same session of the servlet? what is the servlet's logic? dont the two emulators create their own instance of the servlet?

First of all, when you post code, please, use the "code" tags.
I can't test your code but I start to analyse the method startApp() and there is:
userName = new TextField("LoginID:", userName.getString(), 30, TextField.ANY);The object userName is null so
userName.getString()throws a NullPointerException for sure!
Hope this helps.

Similar Messages

  • Servlet/Applet communication, data limit?

    I have an applet that uses a servlet as a proxy to load/retrieve images from an Oracle database. I have a problem when trying to retrieve images larger than 9-10kb from the database. When using JDBC from a Java Application I don't have any probelms but through the Applet-Servlet configuration I do.
    I use the following code in the Applet:
    URL url =new URL("http","myserver",myport,"/servlet/MyServlet");
    HttpURLConnection imageServletConn = (HttpURLConnection)url.openConnection();
    imageServletConn.setDoInput(true);
              imageServletConn.setDoOutput(true);
              imageServletConn.setUseCaches(false);
    imageServletConn.setDefaultUseCaches (false);
    imageServletConn.setRequestMethod("GET");
    byte buf[] = new byte[imageServletConn.getContentLength()];
    BufferedInputStream instr = new BufferedInputStream(imageServletConn.getInputStream());
    instr.read(buf);
    Image image = Toolkit.getDefaultToolkit().createImage(buf);
    // then code to display the image
    And the following for the Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/gif");
    byte[] buff = loadImage(); // this method returns a byte array representing the image.
    response.setContentLength(contentLength);//contentLength is the size of the image
    OutputStream os = response.getOutputStream();
    os.write(buff);
    os.close();
    thanks in advance!

    thanks for your replay,
    I tried your suggestion but whatever I do it seems that tha applet only brings the first 5-10k of the image from the servlet. This is the value I get from instr.read() or any other type of read method. The value of bytes is not always the same.
    Now I also have something new. For images greater than 100k or so I get this error:
    java.io.IOException: Broken pipe
         at java.net.SocketOutputStream.socketWrite(Native Method)
         at java.net.SocketOutputStream.socketWrite(Compiled Code)
         at java.net.SocketOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at org.apache.jserv.JServConnection$JServOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at java.io.FilterOutputStream.write(Compiled Code)
         at interorient.DBProxyServlet.doGet(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at org.apache.jserv.JServConnection.processRequest(Compiled Code)
         at org.apache.jserv.JServConnection.run(Compiled Code)
         at java.lang.Thread.run(Compiled Code)
    I am using the Oracle Internet application server (ias 9i) which actualy uses the apache web listener.
    It seems that this servlet-applet communication is really unstable. If you have anything that may help me it will be greatly appriciated. You can even e-mail me at [email protected]
    thanks!

  • Servlet induced communication

    Hi all,
    I am a java developer that recently turned its attention to j2me. I have recently wrote an application that sends and receives info from a servlet and uses it in a sort of interrup fashion: the server data constraints the mipd app state.
    What I would like to know is, if any of you has written anything like it before, which is the most "elegant" performance-wise way to communicate with a mipd application from a server point-of view.
    I mean, there are many ways to approach this and I would like to know more or to cut out the ludicrous one.
    Some ways I tried were:
    -midp app keeps sending requests to server asking if there is any change and server answers back accordingly (obviously, this is not right)
    -once they pass authentication phase midp and server do not close their input/output streams respectively so that they can keep communicating if need to (this option does not seem to be optimal)
    -server keeps URL of sending midp and uses it whenever it must update its state (this one haven't managed to succeed yet)
    So, I'm listening to comments/criticism if your willing to
    cheers
    j.

    Ok I know that. Now what I meant is do I need to poll the server for new messages (still using the chat-app between midlets example) or can I make both midlets open a connection to the server and send their messages to the server, and have the server redirect the messages to the respective client-midlet. I'm thinking something like each client midlet opens a connection, sends stuff whenever it wants (on the server side, output streams are not closed until some special flag is set) and keeps listening for answers until the user quits or say some special char comes from the server.
    The thing is I'm having some problems when I keep readStreams open after a while (inside a while loop waiting for some special code) and I was wondering if this is valid or is indeed a problem with my code.
    This is what I meant with tunnel before, not really say raw socket comm between midlets but a tunnel through a server that nevertheless kept each midlet from having to poll the ditto all the time. Apologies for not being too clear about it.
    I'm using something like (in pseudo pseudo-code & ommiting all the registration steps etc):
    client midlets
    conn = openConnection();
    out = conn.getOutpuStream();
    in = conn.getInputStream();
    if (!postbox.isEmpty()) {
    msg = removeHead(postbox);
    out.writeStream( sendMessage(msg) );
    ... on a separate thread
    while (USER_IS_ON){
    msg = in.readStream();
    if (msg != null) postbox.add(msg);
    close(conn, out, in);
    Server
    out = request.getOutpuStream();
    in = request.getInputStream();
    data = in.readStream();
    // write this guy's data on the other recipient's queue
    queue.add(data, id);
    ... on a separate thread
    while (USER_IS_ON){
    // get data to this guy from queue
    if (data = hasData(id) != null)
    out.writeStream(data, id);
    close(conn, out, in);
    On fear of making this too long, I'll stop here. I can post the source if you wish but it is rather lenghty :-)
    Thanks for the help!
    cheers
    j.

  • How to debug with EJB+Servlet+J2ME at the same time?

    I am setting up an environment to compile Sun's Smart Ticket J2ME application. However, it run with application exception in the servlet or EJB. I tried to debug. But if I debug the servlet with Embedded AS in JDeveloper, I cannot debug the EJB since the EJB cannot deployed to the embedded AS. (EJB and Servlet must be co-existed in the same AS, at least using same JNDI)
    So is there any good approach to debug?
    email: [email protected]

    Hi Marvin,
    If the EJB cannot be deployed to the embedded AS, then you should probably use remote debugging to debug the servlet and EJB in the stand-alone AS.
    Look in the Help for topics about remote debugging the OC4J application server. (I'd give you the exact topic title, but I'm at home for the holidays and I don't have the latest JDev on this machine.)
    The Help topic describes it in more details, but the basic steps are as follows:
    1. Launch the AS in debug mode by inserting some debugging options on the command line used to start up the AS.
    If you are using OJVM, then the debugging options are
    -XXdebug,port4000,detached
    If you are using another JVM (for example HotSpot), then the debugging options are
    -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=4000,suspend=n
    2. Set your project for remote debugging by checking the Remote Debugging checkbox on the Debugging - Remote panel of the Project Settings dialog. Also you should select the "Attach to OJVM" radio button if you are using OJVM or the "Attach to JPDA" radio button if you are using another JVM (for example HotSpot).
    3. Click the debug button in JDev and enter the host and port where the AS is running (leave host blank if the AS is on the same machine as J[i]Long postings are being truncated to ~1 kB at this time.

  • Database access using servlet MIDlet communication

    Hi all,
    Could anyone please help me?
    I have written a MIDlet connecting to the TOMCAT web server and invokes a Servlet. The Servlet then fetches data (list of names) from MS Sql Server and returns to the MIDlet. Then the MIDlet displays the names in a ChoiceGroup . And MIDlet invokes another servlet to update
    So far everything works well.
    The hard part with this solution is
    1. Servlet has to send the result as delimited strings (with :)
    2. The midlet has to parse the servlet data and extracts the values. this all done through the code only. no routines i used
    3. the url has to have %20 for space otherwise the Connector.open(url) method throws error.
    Can anyone suggest better solutions for this. perhaps easy?
    Regards,
    //Selva

    Ok, so this is the code i use in the MIDlet to post the two parameters, but i can't get them in the servlet. What's wrong?
    HttpConnection c=(HttpConnection)Connector.open(serverURL);
    System.out.println("Connecting");
    c.setRequestMethod(HttpConnection.POST);
    c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dos=c.openDataOutputStream();
    dos.writeUTF("user=" + userName);
    dos.writeUTF("&password=" + password);
    dos.writeUTF("\r\n");
    dos.flush();

  • Servlet applet communication

    I'm having a problem getting a servlet to answer a call from an applet...in the applet I do something like:
    String servlet = "http://192.168.123.148/root/MyServlet.class";
    url= new URL(servlet);
    conn = url.openConnection();
    conn.setUseCaches(false);
    in = conn.getContentLength();
    String contype = conn.getContentType();
    And in the servlet:
    java.io.PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("segment",Integer.toString(99));
    out.flush();
    The problem is I don't get my header back in the applet...and when I look at the content type, its "application/java-vm"...not " text/html"...as I set in the servlet...???

         InputStream urlInput = null;
         HttpURLConnection urlConn =  null;
         URL url = new URL(urlStr);
         urlConn = (HttpURLConnection)url.openConnection();
         urlConn.setDoInput(true);
         urlConn.setDoOutput(true);
         urlConn.setUseCaches(false);
         urlConn.setRequestMethod("POST");
         urlConn.setRequestProperty("Accept-Language", "en");
         urlConn.setRequestProperty("content-type", "text/xml");
         urlInput = urlConn.getInputStream();

  • Servlet-database communication

    Hi,
    I wrote an simple code for an application in which i will communicate servlet-bussinesslogic-database.I was success in the forward manner but when i am trying to return the values from the database to the servlet i am not able to return the values. Can anyone help me out to get the way.
    Note: i am using a simple application where there are no java beans and other stuff...
    please help me out....

    I'm sorry to ask this type of question, but it is necessary , because i'm a student studying the yea B.Tech , I have one problem that is i'm trying to get the data from data base through servlets , but i can load the driver but the connection is not forming between the servlet container and jdbc container but i have one idea about that ,
    i.e. Up to now i tried on the very popular data bases like (Oracle , SQLServer, MySQL,Microsoft Acess)
    But one solution i.e. by ignoring the above mentioned , i want to try the database in the form of xml , for this no need to load the drivers and no need to forn the connections , but we must very well about XML , i don't know how to interact with xml through java application, can any body try it once , if it is success please mention it to my id.

  • Servlet / EJB Communication

              Hello,
              I have a very simple stateless session bean that I've developed for testing. A Client.java class gets the initial context, gets the home interface of the bean, creates the bean, and removes the bean, all without any problems. However, when I instantiate the same client class in a servlet that I've registered in the weblogic.properties file, I get a ClassCastException when the Client casts the Home interface stub into the home interface class. ??? Any idea why I can't successfully use an EJB from within the servlet?
              Thanks in advance,
              Sam
              java.lang.ClassCastException: path.TestSessionBeanBeanHomeImpl_ServiceStub
              

    Sam,
              This is a common problem starting out developing in WebLogic with servlets
              and EJBs. In the J2EE reference implementation and other servers, the WAR
              and JAR both have to contain the home/remote interfaces, since the EJB in
              the JAR needs them and the Servlets in the WAR need them. In WebLogic, to
              support a call-by-reference optimization (and because of some problems in
              the class loader design employed by WebLogic previous to v6), you must NOT
              put them (home/remote) into the WAR file.
              If you do not deploy as WAR and JAR, then just replace WAR with
              "servletclasses" and replace JAR with "serverclasses" in the paragraph
              above.
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com
              +1.617.623.5782
              WebLogic Consulting Available
              "Sam Eubanks" <[email protected]> wrote in message
              news:[email protected]...
              >
              > Hello,
              >
              > I have a very simple stateless session bean that I've developed for
              testing. A Client.java class gets the initial context, gets the home
              interface of the bean, creates the bean, and removes the bean, all without
              any problems. However, when I instantiate the same client class in a
              servlet that I've registered in the weblogic.properties file, I get a
              ClassCastException when the Client casts the Home interface stub into the
              home interface class. ??? Any idea why I can't successfully use an EJB from
              within the servlet?
              >
              > Thanks in advance,
              > Sam
              >
              > java.lang.ClassCastException: path.TestSessionBeanBeanHomeImpl_ServiceStub
              

  • Servlet/Applet Communication and JRE Version

    Hey all,
    I have an applet that sends objects back and forth to a servlet. I have heard that there can be issues if the applet and servlet are run under different versions of java, and right now, the applet works from some machines but not others (I've only tested on PCs so far). I posted a question similar to this a month or two ago, and someone suggested I use UIDs. Can anyone give me some detailed information on how I would do this, or something similar to ensure that any version of Java on someone's machine will work ok, or a link to some helpful info? Thanks.

    Thanks mchan0! I think this will be very helpful.

  • Servlet-JApplet communication

    Hi !
              I am trying to make an application which has to do the following :- An applet( rather a JApplet) has to send a request to servlet to read data from a distant machine using JDBC and then this data should be sent to the JApplet which has to display it in a JTable.
              Please suggest how should I go ahead with this.
              Thanks a lot,
              Charu
              

    tks for your answer,
    but i have not good understood,very much
    so if it's a problem of configuration of server,
    why it run in cas of (doget()),so what's a right configuration ?
    it's not very clear
    u make me pleaser ,if u explain me other one
    tks

  • Servlet jsp communication

    I am little bit new in this field. what I want to do , make a object of a bean in a servlet and put it in request ...then retrieve that from a jsp page.
    And what I did,
    BeanSql1 bq1 = new BeanSql1();
                rs = stmt.executeQuery(sql1);
                if (rs.next()) {
                bq1.setCaptureName(rs.getString(1));
                bq1.setErrorMsg(rs.getString(6));
                bq1.setNegativeRuleSetName(rs.getString(4));
                bq1.setQueueName(rs.getString(2));
                bq1.setRuleSetName(rs.getString(3));
                bq1.setStatus(rs.getString(5));
                rs.close();
                request.setAttribute("bnsql1",bq1);and in jsp,
    <jsp:useBean id="fBean" class="beans.BeanSql1"    scope="request"/>
    <jsp:getProperty name="fBean" property="captureName" />Now....I am not getting the value of "+<jsp:getProperty name="fBean" property="captureName" />"+
    thanx.

    You've created a request scoped bean with the name "bnsql1", but you're trying to access a request scoped bean with the name "fBean".

  • Servlet/swing communication

    how to display data retrieved from oracle using servlet on to the swing GUI?

    Well, how do you want to display it?
    In the form of created graphs? Plain text? Tables? 3D fly-by sequence? Animated smurfs singing the data with cute li'l voices in stereo (where available)?
    There are few practical limits to how you can present the data, really...
    /Fredrik

  • Need Help!  Applet Servlet Portlet Communication

    Hi
    My applet need to send a keyWord to let a portlet to do some operations. I know an applet can communicate with a servlet by URLConnection.But how can portlet? Can I consider a portlet as a servlet and let the applet communicate with the portlet like servlet by URLConnection? could you tell me whether this is possible?
    Thanks for your help.

    Hi
    You have a white-space in the codebase, remove it.
    If that doesn't help, make a static html page, test the Applet with it.
    /Tobias - hopes this helps

  • Servlet Applet object communication problem???!!!

    Hy folks,
    I need to validate the ability of complex Servlet Applet communication an run into my first pb right at the beginning of my tests. I need to have around 200 Applet clients connect to my servlet and communicate by ObjectInput and ObjectOutput streams. So I wrote a simple Servlet accepting HTTP POST connections that return a Java object. When the java Applet get instantiated, the Object Stream communication workes fine. But when the Applet tries to communicate with the servlet after that, I can not create another communication session with that Servlet, instead I get a 405 Method not allowed exception.
    Summarized:
    - Applet init() instantiate URLConnection with Servlet and request Java object (opening ObjectInput and Output Stream, after receaving object, cloasing streams).
    - When I press a "get More" button on my Applet, I am not able to instantiate a new URLConnection with my servler because of that 405 exception, WHY???
    Here my Servlet code:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
             ObjectInputStream inputFromApplet = null;
             ArrayList transmitContent = null;       
             PrintWriter out = null;
             BufferedReader inTest = null;
             try{               
                   inputFromApplet = new ObjectInputStream(request.getInputStream());           
                     transmitContent = (ArrayList) inputFromApplet.readObject();       
                     inputFromApplet.close();
                     ArrayList toReturn = new ArrayList();                 
                     toReturn.add("One");
                     toReturn.add("Two");
                     toReturn.add("Three");
                     sendAnsweredList(response, toReturn);                 
             catch(Exception e){}        
         public void sendAnsweredList(HttpServletResponse response, ArrayList returnObject){
             ObjectOutputStream outputToApplet;    
              try{
                  outputToApplet = new ObjectOutputStream(response.getOutputStream());          
                  outputToApplet.writeObject(returnObject);
                  outputToApplet.flush();           
                  outputToApplet.close();              
              catch (IOException e){
                     e.printStackTrace();
    }Here my Applet code:
    public void init() {         
             moreStuff.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                       requestMore();
             try{
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");              
                  servletConnection = studentDBservlet.openConnection();      
                   servletConnection.setUseCaches (false);
                   servletConnection.setDefaultUseCaches(false);
                   servletConnection.setDoOutput(true);
                   servletConnection.setDoInput(true);
                   ObjectOutputStream outputToApplet;
                 outputToApplet = new ObjectOutputStream(servletConnection.getOutputStream());          
                 outputToApplet.writeObject(new ArrayList());
                 outputToApplet.flush();           
                 outputToApplet.close(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
                  inputFromServlet.close();
                  outputToApplet.close();             
              catch(Exception e){
                   area = new JTextArea();
                   area.setText("An error occured!!!\n");
                   area.append(e.getMessage());
            getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
            getContentPane().add(moreStuff, BorderLayout.SOUTH);
        private void requestMore(){
             try{              
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");                             
                  servletConnection = studentDBservlet.openConnection(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success2!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
              catch(Exception e){               
                   area.setText("An error occured2!!!\n");
                   area.append(e.getMessage());
        }Can someone help me solv this issue please, this is my first Applet Servlet work so far so I have no idea on how to solve this issue.

    Sorry folks, just found my error. Forgot about the ObjectInputStream waiting on the Servlet side, so of course had a dead look...
    Sorry!

  • Tomcat crashes while running servlet chat in IE

    Hi all!
    I've seen similar problems posted about three years ago, but I didn't see an answer for it.
    I'd be very grateful if you could help me.
    I'm writing a chat, the code was taken from the J.Hunter "Servlet programming book" O'reilly, "absurdly simple chat", and adjusted (I only need the Http version). It's an applet-servlet chat.
    When executed in IE, Tomcat crashes after a few (usually 5) sent messages. When executed in a debugger (I use Forte, the last available version, 4 update 1) the program works just fine...
    Another question is about debugging an applet, executed in a browser - how do I do this?
    Here is the code for the servlet:
    =================================
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TryChatServlet extends HttpServlet
    // source acts as the distributor of new messages
    MessageSource source = new MessageSource();
    // doGet() returns the next message. It blocks until there is one.
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    // Return the next message (blocking)
    out.println(getNextMessage());
    // doPost() accepts a new message and broadcasts it to all
    // the currently listening HTTP and socket clients.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    // Accept the new message as the "message" parameter
    String message = req.getParameter("message");
    // Broadcast it to all listening clients
    if (message != null) broadcastMessage(message);
    // Set the status code to indicate there will be no response
    res.setStatus(res.SC_NO_CONTENT);
    // 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 MessageSink().getNextMessage(source);
    // broadcastMessage() informs all currently listening clients that there
    // is a new message. Causes all calls to getNextMessage() to unblock.
    public void broadcastMessage(String message) {
    // Send the message to all the HTTP-connected clients by giving the
    // message to the message source
    source.sendMessage(message);
    // MessageSource acts as the source for new messages.
    // Clients interested in receiving new messages can
    // observe this object.
    class MessageSource extends Observable {
    public void sendMessage(String message) {
    setChanged();
    notifyObservers(message);
    // MessageSink acts as the receiver of new messages.
    // It listens to the source.
    class MessageSink implements Observer {
    String message = null; // set by update() and read by getNextMessage()
    // Called by the message source when it gets a new message
    synchronized public void update(Observable o, Object arg) {
    // Get the new message
    message = (String)arg;
    // Wake up our waiting thread
    notify();
    // Gets the next message sent out from the message source
    synchronized public String getNextMessage(MessageSource source) {
    // Tell source we want to be told about new messages
    source.addObserver(this);
    // Wait until our update() method receives a message
    while (message == null) {
    try { wait(); } catch (Exception ignored) { }
    // Tell source to stop telling us about new messages
    source.deleteObserver(this);
    // Now return the message we received
    // But first set the message instance variable to null
    // so update() and getNextMessage() can be called again.
    String messageCopy = message;
    message = null;
    return messageCopy;
    =============================
    The code for the applet is
    =============================
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class TryChatApplet extends Applet implements Runnable {
    TextArea text;
    Label label;
    TextField input;
    Thread thread;
    String user;
    public void init() {
    // Check if this applet was loaded directly from the filesystem.
    // If so, explain to the user that this applet needs to be loaded
    // from a server in order to communicate with that server's servlets.
    URL codebase = getCodeBase();
    if (!"http".equals(codebase.getProtocol())) {
    System.out.println();
    System.out.println("*** Whoops! ***");
    System.out.println("This applet must be loaded from a web server.");
    System.out.println("Please try again, this time fetching the HTML");
    System.out.println("file containing this servlet as");
    System.out.println("\"http://server:port/file.html\".");
    System.out.println();
    System.exit(1); // Works only from appletviewer
    // Browsers throw an exception and muddle on
    // Get this user's name from an applet parameter set by the servlet
    // We could just ask the user, but this demonstrates a
    // form of servlet->applet communication.
    user = getParameter("user");
    if (user == null) user = "anonymous";
    // Set up the user interface...
    // On top, a large TextArea showing what everyone's saying.
    // Underneath, a labeled TextField to accept this user's input.
    text = new TextArea();
    text.setEditable(false);
    label = new Label("Say something: ");
    input = new TextField();
    input.setEditable(true);
    setLayout(new BorderLayout());
    Panel panel = new Panel();
    panel.setLayout(new BorderLayout());
    add("Center", text);
    add("South", panel);
    panel.add("West", label);
    panel.add("Center", input);
    public void start() {
    thread = new Thread(this);
    thread.start();
    String getNextMessage() {
    String nextMessage = null;
    while (nextMessage == null) {
    try {
    URL url = new URL(getCodeBase(), "/servlet/TryChatServlet");
    HttpMessage msg = new HttpMessage(url);
    InputStream in = msg.sendGetMessage();
    DataInputStream data = new DataInputStream(
    new BufferedInputStream(in));
    nextMessage = data.readLine();
    catch (SocketException e) {
    // Can't connect to host, report it and wait before trying again
    System.out.println("Can't connect to host: " + e.getMessage());
    try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
    catch (FileNotFoundException e) {
    // Servlet doesn't exist, report it and wait before trying again
    System.out.println("Resource not found: " + e.getMessage());
    try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
    catch (Exception e) {
    // Some other problem, report it and wait before trying again
    System.out.println("General exception: " +
    e.getClass().getName() + ": " + e.getMessage());
    try { Thread.sleep(1000); } catch (InterruptedException ignored) { }
    return nextMessage + "\n";
    public void run() {
    while (true) {
    text.appendText(getNextMessage());
    public void stop() {
    thread.stop();
    thread = null;
    void broadcastMessage(String message) {
    message = user + ": " + message; // Pre-pend the speaker's name
    try {
    URL url = new URL(getCodeBase(), "/servlet/TryChatServlet");
    HttpMessage msg = new HttpMessage(url);
    Properties props = new Properties();
    props.put("message", message);
    msg.sendPostMessage(props);
    catch (SocketException e) {
    // Can't connect to host, report it and abandon the broadcast
    System.out.println("Can't connect to host: " + e.getMessage());
    catch (FileNotFoundException e) {
    // Servlet doesn't exist, report it and abandon the broadcast
    System.out.println("Resource not found: " + e.getMessage());
    catch (Exception e) {
    // Some other problem, report it and abandon the broadcast
    System.out.println("General exception: " +
    e.getClass().getName() + ": " + e.getMessage());
    public boolean handleEvent(Event event) {
    switch (event.id) {
    case Event.ACTION_EVENT:
    if (event.target == input) {
    broadcastMessage(input.getText());
    input.setText("");
    return true;
    return false;
    =====================================
    HttpMessage
    ======================================
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class HttpMessage {
    URL servlet = null;
    String args = null;
    public HttpMessage(URL servlet) {
    this.servlet = servlet;
    // Performs a GET request to the previously given servlet
    // with no query string.
    public InputStream sendGetMessage() throws IOException {
    return sendGetMessage(null);
    // Performs a GET request to the previously given servlet.
    // Builds a query string from the supplied Properties list.
    public InputStream sendGetMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = "?" + toEncodedString(args);
    URL url = new URL(servlet.toExternalForm() + argString);
    // Turn off caching
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    return con.getInputStream();
    // Performs a POST request to the previously given servlet
    // with no query string.
    public InputStream sendPostMessage() throws IOException {
    return sendPostMessage(null);
    // Performs a POST request to the previously given servlet.
    // Builds post data from the supplied Properties list.
    public InputStream sendPostMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = toEncodedString(args); // notice no "?"
    URLConnection con = servlet.openConnection();
    // Prepare for both input and output
    con.setDoInput(true);
    con.setDoOutput(true);
    // Turn off caching
    con.setUseCaches(false);
    // Work around a Netscape bug
    con.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
    // Write the arguments as post data
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeBytes(argString);
    out.flush();
    out.close();
    return con.getInputStream();
    // Converts a Properties list to a URL-encoded query string
    private String toEncodedString(Properties args) {
    StringBuffer buf = new StringBuffer();
    Enumeration names = args.propertyNames();
    while (names.hasMoreElements()) {
    String name = (String) names.nextElement();
    String value = args.getProperty(name);
    buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
    if (names.hasMoreElements()) buf.append("&");
    return buf.toString();
    Those files are the only files needed to execute the program.

    The whole Tomcat crashes, and no exception
    displayed.
    Do I have to write the log file, or it's kept by
    Tomcat itself?yes, tomcat writes a log file, you find it in the tomcat dir. but it's just very highlevel. Having a look in it could help.
    Is there a way to write a log file by myself?sure. you could get the log file from tomcat by getting it from the ServletContext:
    ServletContext = getServletContext();
    ServletContext.log("text to log");
    When I view the output window in Forte, it doesn't
    even write that Tomcat crashed.
    I use Tomcat that is installed with the last version
    of Forte(Sun 1 Studio, update 1), I guess it's the
    last version of Tomcat also.No. The lastest is 4.1.12 and i guess it's 4.0.4 with forte.
    Get Tomcat standalone from jakarta.apache.org and try to run your servlet with the standalone tomcat. this could help since i also expirenced problems sometimes with the forte-integrated tomcat.

Maybe you are looking for

  • Supplier site open interface

    Hi, I am working on supplier site open interface. I succesfully loaded data into 'ap_supplier_sites_int' interface table. After submitting supplier site open interface program, it's giving '*Operating Unit Info is null*' error. But, i have operating

  • Ipod not working and I dont know why?

    Can someone please help me? I closed my Ipod cause none of my apps were opening and i closed it and now all its doing is this.. (picture on the bottom) ; It has been doing this for over 20 minutes and i dont know what to do, can anyone help me? somet

  • Customer Invoice Identity

    Hi, I want a customer invoice to be identified on the basis of its creation. (example) CXED Invoice (or) Standard Invoice (or) manual invoice . Can we identify how a customer invoice is generated. Thanks Kenn

  • Why am I having trouble downloading Lion?

    I can not download LION on Centurylink DSL service. Have tried 5 times last and most complete gave me an error message and quit downloading after 6 hours.

  • Java code for Symbol CS2000 scanner

    Hello all, Before I begin to attempt a rewrite of Symbol's C++ code over to Java, I wanted to check in to see if anyone has done this before. I'm looking for (essentially) equivalent functionality to what comes in the SDK with the scanner. Thanks, Do