Solved

problem using applet (and socket)

Posted on 2001-08-29
6
399 Views
Last Modified: 2012-06-21
hi, experts. i have a problem with applet. i make a program that consist of client (applet) and server (application).
if the client using application too, than my program has no problem. the problem in applet is when i want it to loop forever ( using while(true) ) than it's hang (keep download). i know this because if i blocked the 'while' looping (that's will execute only once) than there is no problem occured.


here are the 2 files :
_______________________________________________________
server2.java
-------------------------------------------------
mport java.io.IOException;
import java.net.*;
import java.io.*;

class server2
{
    private static String str = "start receiving data";
    private Socket sock;
    private int counter;

    public static void main(String[] args)
            throws IOException
    {
        ServerSocket servSock = new ServerSocket(8189);
        System.out.println("Server started");
        Socket sock = servSock.accept();

        try
        {
            BufferedReader in = new BufferedReader(
                                new InputStreamReader(sock.getInputStream()));
            PrintStream out = new PrintStream(sock.getOutputStream());
            System.out.println(in.readLine());

            while(true)
                out.println(str);

        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

______________________________________________________
the applet file
-------------------------------------------------
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.Socket;
import java.io.*;

public class clientApplet extends Applet {
    TextArea display;
    private static String host;
    private static Socket sock = null;
    private static PrintStream out = null;
    private static BufferedReader in = null;
     
    public void init() {
         // set the layout
        GridBagLayout gridBag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        setLayout(gridBag);

     // add textarea
        display = new TextArea(10, 20);
        display.setEditable(false);
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.fill = GridBagConstraints.BOTH;
        gridBag.setConstraints(display, c);
        add(display);
       
        getData();
    }
   
    public void getData() {
        try {
            host = getCodeBase().getHost();
            sock = new Socket(host,8189);
            out  = new PrintStream(sock.getOutputStream());
            in   = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            display.append("Waiting Data from server...");
            out.println("client");

            while (true)                 //the problem
                display.append("\n--> Data from server : " + in.readLine());

        } catch (java.net.UnknownHostException e) {
            display.append("Can't find host");
        } catch(java.io.IOException e) {
            display.append(e.toString());
        } catch(java.lang.Exception e) {
            display.append(e.toString());
        }
    }
}
_______________________________________________________


if u have test it, u will agree with me that the problem is in the 'while' loop, inside the loop, i put 'in.readLine()' command that will waiting for server input, so the applet should be waiting , not running.

hope u guys can help me, thanx.


regards,
sky.
0
Comment
Question by:skyjamz
  • 3
  • 3
6 Comments
 
LVL 92

Expert Comment

by:objects
ID: 6435737
Your applet will never get past initialising, and start() won't get called.

Call getData() in start() not init().
0
 

Author Comment

by:skyjamz
ID: 6439288
i have change the code like this :

________________________________________________________
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.Socket;
import java.io.*;

public class clientApplet extends Applet {
    TextArea display;
    private static String host;                                        // setting localhost name
    private static Socket sock = null;
    private static PrintStream out = null;
    private static BufferedReader in = null;
     
    public void init() {
         // set the layout
        GridBagLayout gridBag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        setLayout(gridBag);

     // add textarea
        display = new TextArea(10, 20);
        display.setEditable(false);
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.fill = GridBagConstraints.BOTH;
        gridBag.setConstraints(display, c);
        add(display);
    }
   
    public void start() {
        getData();
    }
   
    public void getData() {
        try {
            host = getCodeBase().getHost();                                              //Get the address of the host we came from.
            sock = new Socket(host,8189);                              // connect to the server
            out  = new PrintStream(sock.getOutputStream());                    // get stream
            in   = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            display.append("Waiting Data from server...");
            out.println("client");                                   // send data to server telling that itself is a client
           
            while (true)                                         // looping forever
                display.append("\n--> Data from server : " + in.readLine());          // getting data from server
               
        } catch (java.net.UnknownHostException e) {
            display.append("Can't find host");
        } catch(java.io.IOException e) {
            display.append(e.toString());
        } catch(java.lang.Exception e) {
            display.append(e.toString());
        }
    }
}
________________________________________________________

it's getting better, it's stop initialized, but still there are no respond, and if i blocked or delete the 'while(true)' than it goes normal.

regards,
sky.
0
 
LVL 92

Accepted Solution

by:
objects earned 200 total points
ID: 6439337
Sorry I missed the full extent of the problem originally.

What you need to do is run getData() in a seperate thread.

Something like:

public void start()
{
  new Thread(new Runnable()
    { public void run() { getData(); }}).start();
}


0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:skyjamz
ID: 6439606
wow, it's really work ! i'm really really happy, thanks alot, i think i adore u, OBJECTS, :) .

u have ease my job. i have dealed with that error for three days.

but could u explain more why it hangs ? and why i must run getData() is a separate method ?

i really appreciate your help, thank a lot.

regards,
sky.
0
 
LVL 92

Expert Comment

by:objects
ID: 6439639
> thanks alot, i think i adore u

You're 2 kind.

> but could u explain more why it hangs ?

You were calling getData from the thread that handles updating your gui. So because getData never returns your gui never gets updated.

> and why i must run getData() is a separate method ?

By running getData in a seperate thread, you have two threads of execution, one handling talking to the server, and the other handling your gui.


Happy to be of assistance.
Thanks for the points :)
0
 

Author Comment

by:skyjamz
ID: 6439683
thank u for your explanation, it's really help me, hope u can help me next time :)

regards,
sky.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now