Servlet/applet/socket problem

Hi there,
my problem is this...
i create a page with an servlet whicht shows an applet. this applet connects to a server through an socket. it works fine, but, when i change the page and the applet is not longer on the screen, the socket connection will be not killed! i dont know why. but i must kill it when the applet is not longer on the screen...whats wrong? can you help me?
matthias

Are you overriding the destroy() method in your Applet? This will be called when the applet is about to be unloaded from the browser. Or, as a slightly different alternative, you can override the stop() method, which is called when the applet is scrolled off the screen. Usually when stop() is used, start() is overriden as well to allow the applet to resume when it is scrolled back into view. For more info, read up on the applet lifecycle.

Similar Messages

  • Applet socket problem in client-server, urgent!

    Dear All:
    I have implemented a client server teamwork environment. I have managered to get the server running fine. The server is responsible for passing messages between clients and accessing Oracle database using JDBC. The client is a Java Applet. The code is like the following. The problem is when I try to register the client, the socket connection get java.security.AccessControlException: access denied(java.net.SocketPermission mugca.its.monash.edu.
    au resolve)
    However, I have written a Java application with the same socket connection method to connect to the same server, it connects to the server without any problem. Is it because of the applet security problem? How should I solve it? Very appreciate for any ideas.
    public class User extends java.applet.Applet implements ActionListener, ItemListener
    public void init()
    Authentication auth = new Authentication((Frame)anchorpoint);
    if(auth.getConnectionStreams() != null) {
    ConnectionStreams server_conn = auth.getConnectionStreams();
    // Authenticates the user and establishes a connection to the server
    class Authentication extends Dialog implements ActionListener, KeyListener {
    // Object holding information relevant to the server connection
    ConnectionStreams server_conn;
    final static int port = 6012;
    // Authenticates the user and establishes connection to the server
    public Authentication(Frame parent) {
    // call the class Dialog's constructor
    super(parent, "User Authentication", true);
    setLocation(parent.getSize().width/3, parent.getSize().height/2);
    setupDialog();
    // sets up the components of the dialog box
    private void setupDialog() {
    // create and set the layout manager
    //Create a username text field here
    //Create a password text field here
    //Create a OK button here
    public void actionPerformed(ActionEvent e) {
    authenticateUser();
    dispose();
    // returns the ConnectionStreams object
    public ConnectionStreams getConnectionStreams() {
    return(server_conn);
    // authenticates the user
    private void authenticateUser() {
    Socket socket;
    InetAddress address;
    try {
    // open socket to server
    System.out.println("Ready to connect to server on: " + port);
    socket = new Socket("mugca.its.monash.edu.au", port);
    address = socket.getInetAddress();
    System.out.println("The hostname,address,hostaddress,localhost is:" + address.getHostName() + ";\n" +
    address.getAddress() + ";\n" +
    address.getHostAddress() + ";\n" +
    address.getLocalHost());
    catch(Exception e) {
    displayMessage("Error occured. See console");
    System.err.println(e);
                                  e.printStackTrace();
    }

    Hi, there:
    Thanks for the help. But I don't have to configure the security policy. Instead, inspired by a message in this forum, I simply upload the applet to the HTTP server (mugca.its.monash.edu.au) where my won server is running. Then the applet is download from the server and running fine in my local machine.
    Dengsheng

  • Applet & socket problem

    I want to request Socket port (23)and exchange string from Applet program
    When I try this program , java security exception occur
    how I can use port 23 from Applet
    thanks

    you either have to sign your applet or change you java.policy file to allow the applet to use the socket. to edit the policy file you can use policytool or a text editor.
    more info can be found at http://java.sun.com/docs/books/tutorial/security1.2/summary/tools.html

  • 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!

  • 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!

  • Applet - Servlet - Database - Servlet- Applet

    Hi All,
    I am using Oracle8i and IE 5.0. I am trying to retrieve the data from a db table and display it.
    Sequence is as following:
    1. Query passed to the applet.
    2. Servlet excutes this query using JDBC and returns the resultset to applet.
    3. Applet displaysthe results.
    Is there anybody who has a code sample to do this, my id is [email protected] ? I am totally new to java and servlets. I would really appreciate any help.
    Thanks a lot.
    Manuriti
    [email protected]

    I've never dealt with the code to handle the applet portion of what you're trying to do, but I can help you with the servlet stuff.
    Your servlet should contain code to accomplish the following steps:
    1. Load an Oracle JDBC driver into memory.
    2. Open a JDBC connection to the Oracle database.
    3. Create a JDBC Statement object which contains the appropriate Oracle SQL code.
    4. Execute the Statement object, which will return a ResultSet.
    5. Read the ResultSet data.
    6. Pool or close the Statement and Connection objects.
    All of these steps are simple. Here's what they might look like in practice:
    // load the Oracle driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // open the connection
    String cs = "jdbc:oracle:[email protected]:1521:DBNAME"; // connection string
    String userName = "scott";
    String password = "tiger";
    Connection con = DriverManager.getConnection(cs, userName, password);
    // create a Statement object
    Statement stmt = con.createStatement();
    // create a ResultSet object
    ResultSet rs = stmt.executeQuery("select * from DUAL"); // your SQL here
    // INSERT CODE HERE TO READ DATA FROM THE RESULTSET
    // close the Statement object
    stmt.close();
    // close the Connection object
    con.close();
    So that's how you get data from your Oracle database. Now, how do you pass it to your applet? Well, this is hardly trivial. Typically, servlets return an HTML-formatted text stream. It is possible to have an applet communicate with a servlet, but that raises security issues that I don't fully understand. I believe you would have to have your user's browsers set to the lowest possible security settings, otherwise the browser won't let the applet open a socket to a foreign IP, but again, I'm shaky on that one.
    Anywho, let me know if this was of help and if you have more questions on the servlet/applet stuff. I can probably help you with more specific questions,.

  • Applet socket server

    Is it possible to have applet socket server? if so, pls tell me the method. Thanks.
    regards,
    Bala

    applet socket server?hmm...i dont think so...this will produce an exception... but maybe you can try signing the applet....

  • Applet running problem in ie 6.0 under Windows XP

    Applet running problem in ie 6.0 under Windows XP
    I have a PC running Iternet Explorer 6.0 running under Windows XP. I have developed an applet using JDK 1.3 which is running fine with applet viewer , but it is not running in ie. I have installed Netscape navigator and Opera 5. the applet is running fine in both of these browsers but somehow it is not running in IE.
    Later on I upgraded my JDK to 1.4. It also displays use Java2 (V1.4.1) for <applet> (requires restart) tck marked in Advance section under Tools-Options menu of IE.
    I have also tried and set various options in my Control Panel�s Java Plug-in but all in vain. I have searched the sites for this solution but no one answers specifically.
    I know it�s a small problem due to discarded JVM in IE under Windows XP but give me solution for that.
    Thanks in Advance
    [email protected]

    Dear I have the same problem .
    Applet running problem in 6.0 . Enen I have installed the latest Jre 1.5.
    What should I do. I am fedup with this problem.

  • Applet Flash problem

    I have an applet and a flash in two frames in a HTML page. The applet and the falsh app communicate through the Javascript code with in the HTML pages. The flash app does not work as it is supposed to when the applet is present in the Parent HTML page. When I removed the applet, the flash app seems to work ok. But the applcation that I am working needs both of them together. Plz suggest me a solution if you know of any flash and applet related problems.
    Thanks in advance.
    kris

    http://forum.java.sun.com/thread.jsp?forum=31&thread=378703&start=0&range=15#1618263

  • Servlet/applet problem

    hi guys
    my problem is that, i started my tomcat server, also my servlet. this servlet should call an applet. so here are my questions:
    where must be the applet class file?
    how looks like my codebase?
    what code must i type into the servlet? something special?
    do i need an apache server additional?
    yes? where must be my files? :)
    hope anyone can help me...
    bye

    keep the applet class file in the home directory, the directory in which your index.html lies, index.html -- the html which shows up when you say http://localhost:8080
    and then give the applet description like this in the servlet
    out.println("<applet code=\"myApplet.class\" codebase=\"http://localhost:8080\" width=\"400\" height=\"400\"> ");
    out.println("</applet>");
    and that should work and you will be good to go

  • Applet Servlet Comm. Problem

    Dear friends,
    i have an applet that sends a serialized object to the servlet,the Servlet creates another object and passes it back to the applet.
    Everything works fine, till i read the object with:
    ObjectInputStream objInputStream = new ObjectInputStream(in);
            show("got object input stream");
             chart = new ChartPanel((JFreeChart)objInputStream.readObject());At this point, i got nothing back.Instead i get a "null"returned on my Java Console.
    From JBuilder it works fine
    Here is the code
    //This is called from the applet in order to load a chart in a panel
    private JPanel getChartFromServlet(Object[] parameters) throws Throwable {
      ChartPanel chart=null;
      String server;
       try {
    ///////////////////////create URL Connection to SERVLET
        if (this.remoteServerMode) {
          this.show("http://10.30.1.38:8080/AppletToServlet/DbServlet");
           server="http://10.30.1.38:8080/AppletToServlet/DbServlet";
         else {
           server="http://localhost:8083/DbServlet";
         //SEND DATA TO SERVLET
         URLConnection servletCon=this.getServletConnection(server);
         // servletCon.setRequestProperty("Content-Type","application/octet-stream");
          //send the query parameters  using serialization
           ObjectOutputStream out=new ObjectOutputStream(servletCon.getOutputStream());
           out.writeObject( parameters);
           out.flush();
           out.close();
           this.show("Finish with send to servlet");
           //GET DATA FROM SERVLET
           InputStream in=servletCon.getInputStream();
           show("got input stream");
           ObjectInputStream objInputStream = new ObjectInputStream(in);
            show("got object input stream");
             chart = new ChartPanel((JFreeChart)objInputStream.readObject());
             show("got chart");
            objInputStream.close();
            in.close();
            chart.setPreferredSize(new Dimension(734, 370));
       catch (Exception ex) {
         System.err.println("Exception caught");
         this.show(ex.getMessage());
         this.show(ex.getMessage());
         System.err.println(ex.getMessage());
         ex.printStackTrace(System.err);
       throw new Exception( ex.getCause());
    return chart;
    //Servlet Side Code
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
        ObjectInputStream inputStreamFromApplet=null;
        Object[] queryParams;
      JFreeChart chart=null;
        try {
          response.setContentType("application/x-java-serialized-object");
          //////////////////////////READ INPUT//////////////////////////////////////
          InputStream in=request.getInputStream();
          inputStreamFromApplet=new ObjectInputStream(in);
          //Read applet's serialised object passed in Input Stream
          queryParams = (Object[]) inputStreamFromApplet.readObject();
          //do something with serialized object
          chart=getRequestedChart(queryParams);
          //////////////////////////WRITE OUTPUT////////////////////////////////////
          //open an output stream
          ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
          //write to output stream
          out.writeObject(chart);
          out.flush();
          //close output stream
          out.close();
        catch (Exception ex) {
          ex.printStackTrace();
          System.err.println(ex.getMessage());
      }Do you have any ideas?
    Apart from the null value,i saw also some SocketException
    Is there a security issue involved?Both Servlet and Applet come from the same ip.
    Thank you very much in advance,
    Chris

    A Chart constructor takes as an arg a JFreeChart.
    Chart is a JComponent so i cannot serialize it.
    That's why the servlet passes a JFreechart object and
    the applet constructs a chart from it.
    I cast the object to a jfreechart and pass it to the constructor of the chart.
    The strange thing also is that, wghile initially with a non perfectly designed UI,everything worked fine but when i modified the applet's UI ,problems started...
    Something with serialization and versions of classes?

  • Servlet-Applet project. Architectural problem.

    Hello, everybody!
    I'm to make client-server web project, client works with different databases via server (using servlet). The protocol of the project is as follows:
    - Client requests to �erver and gets applet.
    - All communications between client and server are to be made via applet-servlet. So, client makes some operations using applet, then sends data to server. After the data being processed on the server side, client gets the possibilities to make further operations.
    The problem is choosing the proper architecture. Having sigle applet and processing communications with single applet-servlet is not good, because I need to get client the possibility to choose database, then choose table, edit records and so on. I want to have applets for every type of operations. I mean, after client gets start applet, he sends the request to server, which processes it and gets another applet for database choosing and so on.
    The question is: is it possible to build such architecture with many applets and data transfers between them?

    Why does it need to be through applet?
    Why can't the same applet take care of most (all?) your database chores?

  • Applet Socket permission problem

    Heloo I made an applet which gets the content of web . like if i pass the www.yahoo.com to applet it must read all the html coding of yahoo page .my code is perfect with the desktop application but when i run it with applet then it gives the socket permission error i search all where but i havent found any solution i tried to edit policy file but still found the same error kindly help me how to get rid from this error thanks and below is my code sample
    Applet code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.security.Permission;
    public class Apple extends JApplet implements ActionListener{
              Container c;
         JTextField uf=new JTextField(30);
         JTextArea tarea=new JTextArea(600,600);
         JButton b=new JButton("Get Content");
         JButton bb=new JButton("Clear");
         URL u;
         JScrollPane sp=new JScrollPane();
         InputStream is = null;
    DataInputStream dis;
    String s;
         public void init(){
              JOptionPane.showMessageDialog(null,"hello world");
              c=new Container();
                   JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
              c=this.getContentPane();
              uf.setText("http://www.yahoo.com");
              c.setLayout(new FlowLayout(FlowLayout.LEFT));
              sp.add(tarea);
              c.add(new JLabel("Enter Your Url"));
              c.add(uf);
              c.add(b);     c.add(bb);
              c.add(new Label("EXAMPLE: http://www.rentacoder.com"));
              b.addActionListener(this);bb.addActionListener(this);
              c.add(tarea);     
         public void actionPerformed(ActionEvent ae){
              if( ae.getSource()==b){
                        JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
              down();
              if( ae.getSource()==bb){
    tarea.setText("");
              public void down(){
                   try{
                   System.out.println("1");
                   String uu=uf.getText()+":80";
                   u = new URL(uf.getText());
                   is = u.openStream();
                   dis = new DataInputStream(new BufferedInputStream(is));
                   String str;int k=0;int l=50;
                   while ((s = dis.readLine()) != null) {
    tarea.append(s+"\n");
    k++;
    if(k==l){
         JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
    l=2*k;
    }is.close();
    } catch (MalformedURLException e) {JOptionPane.showMessageDialog(null,"e"+e);
    } catch (IOException e) {JOptionPane.showMessageDialog(null,e);
    HTML CODE :
    <applet code="Apple.class" width="300" height="300">
    </applet>

    The applet should be able to connect to the host it came from but I think you
    have to connect to the same port as well (not really sure about that).
    You can either have the consumers of your applet set up a policy for your applet
    or you sign the applet.
    Signing applets:
    http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
    second post and last post for the java class file
    http://forum.java.sun.com/thread.jsp?forum=63&thread=409341
    4th post explaining how to set up your own policy with your own keystore
    Java security configuration (according to me):
    1. Signing, good for Internet published applets. The user will be asked if he or she trusts
    the applet and when yes or allways is clicked the applet can do whatever it wants. This
    is the default setting of the SUN jre and can be compared with IE setting that askes the
    user about downloading and running ActiveX controls from the Internet security zone.
    2. Setting up a policy. Good for people who disabled asking the user about signed
    applets (like companies that are worried this could cause a problem). it is possible
    to provide multiple java.policy files in the java.security, a company could put a .policy file
    on the Intanet and have all jre's use this by adding this URL to the java.security.
    When a policy needs to be changed the admin only has to do this is the file on the
    Intranet.
    A specific user can have a policy in their user.home to set up personal policies (to be
    done by Administrators).
    A policy file can use a keystore to be used in a signed by policy. For example "applets
    that are signed by SUN can access some files on my machine). It can allso be used
    to identify yourselve, when making an SSL connection the keystore can be used as
    the source of your public key.

  • Applet - Server socket problem

    Hello i'm trying to develop a simple chat application
    The applet connects to the server via a socket and it can successfully send a line of text to the server and receive one back.
    But if I try to put a loop in to receive more lines the applet doesn't start
    here is some source, i'd appreciate any help
    * ChatClient.java
    * Java Applet for communicating with server
    import java.io.*;
    import java.net.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ChatClient extends Applet
         public Panel input;
         public OutputPanel output;
         public PrintWriter out = null;
    public BufferedReader in = null;
         public Socket client = null;
         public Label label;
         public TextField itext;     
         public boolean connected = false;
         public String fromServer = "";
         public void init()
              setLayout( new BorderLayout() );
              input = new Panel();
              input.setLayout( new FlowLayout() );
              label = new Label( "Enter Message" );
              itext = new TextField( 15 );
              TextHandler handler = new TextHandler();
              itext.addActionListener( handler );
              input.add( label );
              input.add( itext );          
              output = new OutputPanel();     
              add( "South", input );
              add( "Center", output );
         public void start()
              String host = getDocumentBase().getHost();          
              try
                   // create socket connection
                   client = new Socket( host, 4444 );
                   out = new PrintWriter( client.getOutputStream(), true );
    in = new BufferedReader( new InputStreamReader( client.getInputStream() ) );
              catch (UnknownHostException e)
                   System.err.println("Don't know about host: 10.1.7.2.");
    System.exit(1);
              catch (IOException e)
    System.err.println("Couldn't get I/O for the connection to: 10.1.7.2.");
    System.exit(1);
              output.otext.append( "Chat client started, listening\n\n" );
              listen();               
         public void listen()
              out.println( "Client 1" );
              try
                   fromServer = in.readLine();
                   output.otext.append( "Server: " + fromServer + "\n\n" );
                   connected = true;
                   //do
                   //     fromServer = in.readLine();
                        System.err.println( "Server: " + fromServer );
                   //     if ( fromServer.equals( "Bye" ) )
                   //          connected = false;
                   //     output.otext.append( "Server: " + fromServer + "\n\n" );
                   //}while ( connected );
              catch( IOException io )
                   System.err.println( "Cannot read from server" );
                   io.printStackTrace();
         public void sendData ( String s )
              out.println( s );
              //output.otext.append( "Client: " + s + "\n\n" );
         public void destroy()
              try
                   out.println( "Bye" );
                   out.close();
                   in.close();
                   client.close();
              catch( IOException io )
                   System.err.println( "Error closing Socket or IO streams");
                   io.printStackTrace();
    class TextHandler implements ActionListener
         public void actionPerformed( ActionEvent e )
              sendData( e.getActionCommand() );
    public String getAppletInfo()
              return "A simple chat program.";
         public static void main(String [] args)
              Frame f = new Frame( "Chat Applet" );
              ChatClient chatclient = new ChatClient();
              chatclient.init();
              chatclient.start();          
              f.add( "Center", chatclient );
              f.setSize( 300, 300 );
              f.show();
    class OutputPanel extends Panel
         public TextArea otext;
         public OutputPanel()
              setBackground( Color.white );
              setLayout( new BorderLayout() );
              otext = new TextArea( 6, 60 );
              otext.setEditable( false );
              add( "Center", otext );
              setVisible( true );
    public void paint(Graphics g)
    }

    I think you have to modify the loop, which receive data from your socket.
    here an example which I tryed
    hope I can help you
    while (z==1)
    anzeige = in.readLine();
    if (anzeige.charAt(0) == ende.charAt(0) && anzeige.charAt(1) == ende.charAt(1) && anzeige.charAt(2) == ende.charAt(2)) // searching for the end"-~-"
    break;
    textField.add(anzeige);

  • Servlet Server Socket Communication problem

    Hi
    Iam having this problem ...when I read data in server line by line it works but when I try to read byte by byte server hangs. This is my code
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    clientSocket.getInputStream()));
    //it works fine when i do
    String strLine = in.readLine();
    //but hangs when I do like this
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int r = in.read();
    while(r != -1)
    baos.write(r);
    r = in.read();
    I am sending data from the client socket as
    out = new PrintWriter(addArtSocket.getOutputStream(), true);
    I just do out.println to send data.
    Is there something wrong that I am doing?
    Thanks
    vinitha

    hi,
    basically, I suggest that you have the communication
    channel in the same type between two ends. For example,
    if you decide to connect two side byt Stream, you just
    apply your code in the sort of Stream for I/O.
    If you decide to connect two sides by Reader/Writer, you
    apply your code in the sort of Reader/Writer for I/O.
    Don't mix them up. Although I don't know what may
    happen. For example, you want to pass an Object
    between two ends, you could use ObjectInputStream/
    ObjectOutputStream pair on two sides. Don't put
    ObjectInputStream in one side and talk to one sied
    which write data by other OutputStream filteer but
    not ObjectOutputStream .
    You may find something interesting.
    good luck,
    Alfred Wu

Maybe you are looking for