
import java.awt.Graphics;
import java.io.*;
import java.net.*;
import java.net.Socket;

public class Polling extends java.applet.Applet 
		implements Runnable {
	Thread runner = null;
	String host = "j2";
	int	port = 9091;
	String SendingData = "/";
	String id = "0";

	public void start() {
	String name;
		if ( runner == null ) {
			name = getParameter("host");
			if ( name == null )
				name = "localhost";
			host = name;
			name = getParameter("port");
			if ( name == null )
				port = 9091;
			else	port = Integer.parseInt(name);
			name = getParameter("id");
			if ( name == null )
				id = "0";
			else	id = name;

			runner = new Thread(this);
			runner.start();
		}
		name = getParameter("sendData");
		if ( name == null )
			SendingData = "/";
		else	SendingData = name;
	}

	public void stop() {
		SendingData = "other";
		try { Thread.sleep(2000); }
		catch (InterruptedException e) {}

		runner.stop();
	}

	public void paint(Graphics g) {
		g.drawString("HTML Viewer for GLOBALBASE COSMOS",5,25);
	}


	public void run() {
		String name;
		Socket  conn = null;
		DataInputStream in = null;
		DataOutputStream out = null;
		String line;
		boolean end;
		URL theURL;

		end = true;
		for ( ; end ; ) {

			try { Thread.sleep(1000); }
			catch (InterruptedException e) {}

			try {
				conn = new Socket(host,port);
				if ( conn == null )
					continue;
				in = new DataInputStream(
					new BufferedInputStream(
					conn.getInputStream()));
				out = new DataOutputStream(
					new BufferedOutputStream(
					conn.getOutputStream()));
				if ( in == null )
					continue;
				if ( out == null )
					continue;
				out.writeBytes("*POLLING " +
					id + " " + SendingData + "\n");
				out.flush();
				line = in.readLine();
				if ( line != null ) {
					if ( Integer.parseInt(line)
							== 0 ) {
						runner.stop();
						runner = null;
						end = false;
					}
					if ( Integer.parseInt(line)
							== 2 ) {
						line = in.readLine();
						if ( line != null ) {
							theURL = null;
							try {theURL = new URL(line);}
							catch ( MalformedURLException e) {}
							if ( (getAppletContext() != null) && 
							   ( theURL != null) ) {
								getAppletContext().
									showDocument(theURL);
							}
						}
					}
					while ((line = in.readLine())
							!= null ) {
						System.out.println
							(line + '\n');
					}
				}
				conn.close();
			}
			catch (IOException e) {
				System.out.println("IO ERROR: "
				+ e.getMessage());
			}
		}
	}
}
