//
// MonitoraUsu.java
//

package client;

import java.net.*;
import java.io.*;

public class MonitoraUsu extends Thread {

	ServerSocket CliSocket = null;
	int portClient;
	int portServer;

public MonitoraUsu()
{
	try
	{
		CliSocket = new ServerSocket(2000);
	} catch (Exception e)
	{
		e.printStackTrace();
	}
	System.out.println("Monitorando porta 2000");
	this.start();
}

public void run()
{
	try
	{
		while(true)
		{
			Socket client = CliSocket.accept();
			handleClient(client);
			client.close();
		}
	}
	catch (IOException e)
	{
	System.out.println("Exception while listening for connection");
	}
}

void handleClient( Socket s) throws IOException
{

	String line = null;
	String strGet = null;
    BufferedReader from =	new BufferedReader(new
		    InputStreamReader(s.getInputStream()));
    line = from.readLine();

	System.out.println("solicitado: " + line);

	reply(strGet, s);

}



public void reply(String strUrl, Socket s)
{
	System.out.println("reply " + strUrl);

//
//	Boolean PedirOpiniao = aqui entra um metodo a ser desenvolvido;
//
//  Se devo pedir opiniao do usuário tenho que inserir na página um
//  applet...mais ou menos assim:
//
//<BODY><APPLET code=opniao.class width = 0 height = 0></APPLET> </BODY></HTML>


	byte[] bytLeitura = new byte[4096];
	int intLido;
	try
	{
	URL url = new URL(strUrl);
	URLConnection conexao = url.openConnection();
	DataInputStream inpLer = new DataInputStream(conexao.getInputStream());
	DataOutputStream out = new DataOutputStream(s.getOutputStream());
	while ((intLido = inpLer.read(bytLeitura)) > -1)
	{
		out.write(bytLeitura, 0, intLido);
	}

	out.flush();
	out.close();
	inpLer.close();
	} catch (Exception ex){
		ex.printStackTrace();
	}
}



public static void main(String []args)
{
	MonitoraUsu s = new MonitoraUsu();
}

}


