Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Are Threads the answer?

Status
Not open for further replies.

modalman

Programmer
Feb 14, 2001
156
GB
Hi. I've written an applet that contacts a remote server for information using ftp. Sometimes that server doesn't respond which will make my applet hang up. Only closing the browser down can stop it.
Is there a way that I can time the server response and if nothing happens after say 60 secs then the applet stops waiting for the server. Would I need 2 threads for this. One to act as a timer and the other to contact the server and when the timer thread deems it necessary it will then stop the connection thread. Does that make sense?
Many thanks in advance. ASCII silly question, get a silly ANSI
 

Hey,

Using threads is possibly the best way to make the
connection to the server so that the rest of the
applet doesn’t hang. I’m not sure of the logic,
but your applet has to implement the Runnable
interface to make use of threading.

Code:
import java.applet.*;

public class MyApplet extends Applet implements Runnable
{
	Thread connection;
	int attempts = 0;

	public void init()
	{
		connection = new Thread(this);
		connection.start(); // Calls run() method.
	}

	public void run()
	{
		synchronized(this)
		{
			// Connection code.
		}

		if (/* connection established */)
		{
			connection.stop();
		}
		else
		{
			// Try to connect again and wait 60 seconds.
			connection.sleep(60000)

			attempts++;

			// After 3 attempts of connecting and no success, abort.
			if (attempts == 3)
			{
				connection.stop();
			}
		}
	}
}

karmafree.
 
Won't this cause a security exception for any address
other than the server from which the applet was loaded?
 
Haha, sercurity exceptions, those always bug me. There is a way to get around that I'm sure. I had to do that when I used RMI and JDBC. Unfortunately, it has been a while and I can't exactly remember code. But I do remember that you have to create a policy file and load it into your applet. Something like:

grant codeBase <url in quotes>
{
permission java.io.FilePermission <dir>,&quot;read,write&quot;;
}

Opps I just realized that this is for read/write to a different url. Well anyway this should help a little. As for the connection, I cannot think of a security exception there.
 
Thanks Guys. I am using a signed Applet and have already set various Permissions for ftping using a client side port. But if things go wrong I'll bear that in mind. Thanks karmafree for the code. I think that should do it. ASCII silly question, get a silly ANSI
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top