Criar um main para classe

Ola galera

Alguem sabe como que tem que s er o main da se guinte classe:

package br.com.farzac;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.Socket;

public class ClientSocket implements Runnable
{
private String remoteHost = “192.168.200.201”;
private int remotePort = 2101;
private Object parent;
private String name;
private DataInputStream read;
private DataOutputStream write;
private Thread clientThread;
protected Socket client;
private Method onReceiveMethod;
private Method onSendMethod;
private Method onConnectMethod;
private Method onDisconnectMethod;
private boolean running = false;

/**

  • Construtor parent
    */
    public ClientSocket(ClientSocketInterface parent, String name)
    {
    this.parent = parent;
    this.name = name;
    loadMethods();
    }

/**

  • Cria o Client socket com a configuracao
  • @param parent
  • @param RemoteHost
  • @param RemotePort
    */

public ClientSocket(ClientSocketInterface parent, String name, String RemoteHost, int RemotePort)
{
this.remoteHost = RemoteHost;
this.remotePort = RemotePort;
this.parent = parent;
this.name = name;
loadMethods();
}

/**

  • Configura a classe a estabelece conexão com o host
    */

public void connect() throws IOException, ConnectException
{
System.out.println("Iniciando conexão com host: " + remoteHost);
client = new Socket(remoteHost, remotePort);
setStreams();
running = true;
clientThread = new Thread(this);
clientThread.start();
notifyOnConnect();
// new Thread(new VerifyConnection(this));
System.out.println(“Conexão aberta com sucesso”);
}

/**

  • Configura a classe e estabelece conxão com o host
  • @param String RemoteHost
  • @param int RemotePort
    */
    public void connect(String RemoteHost, int RemotePort)throws IOException
    {
    this.remoteHost = RemoteHost;
    this.remotePort = RemotePort;
    this.connect();
    }

/**

  • Encerra a conexão com o host
    */
    public void disconnect()
    {
    try
    {
    System.out.println(“Fechando a conexão…”);
    running = false;
    client.close();
    write.close();
    read.close();
    notifyOnDisconnect();
    clientThread.stop();
    }
    catch(IOException ioe)
    {
    System.out.println(“Erro ao fechar a conexão”);
    }

}

/**

  • Processa os eventos da conexão
    */

public void run()
{
byte[] received = new byte[1024];
int lenFrame;
do
{
try
{
lenFrame = read.read(received);
notifyOnReceived(new String(received,0,lenFrame));
}
catch(Exception ioe)
{
if (running)
disconnect();
}
}while(running);
}

/**

  • Carrega os métodos de tratamento de eventos da conexão
    */
    private void loadMethods()
    {
    Class parentClass = parent.getClass();
    System.out.println(“Carrengando os metodos…”);
    try
    {
    onReceiveMethod = parentClass.getMethod(“ClientSocketOnReceive”,ClientSocket.class,String.class);
    System.out.println(“Metodo ClientSocketOnReceive carregado com sucesso”);
    }catch(NoSuchMethodException nsme)
    {
    System.out.println(“Erro ao carregar o metodo ClientSocketOnReceive”);
    }
    catch(Throwable tab)
    {
    System.out.println(“Erro ao carregar o metodo ClientSocketOnReceive”);
    }
    try
    {
    onSendMethod = parentClass.getMethod(“ClientSocketOnSend”, ClientSocket.class);
    System.out.println(“Metodo ClientSocketOnSend carregado com sucesso”);
    }catch(NoSuchMethodException nsme)
    {
    System.out.println(“Erro ao carregar o metodo ClientSocketOnSend”);
    }
    try
    {
    onConnectMethod = parentClass.getMethod(“ClientSocketOnConnect”, ClientSocket.class);
    System.out.println(“Metodo ClientSocketOnConnect carregado com sucesso”);
    }catch(NoSuchMethodException nsme)
    {
    System.out.println(“Erro ao carregar o metodo ClientSocketOnConnect”);
    }
    try
    {
    onDisconnectMethod = parentClass.getMethod(“ClientSocketOnDisconnect”, ClientSocket.class);
    System.out.println(“Metodo ClientSocketOnDisconnect carregado com sucesso”);
}catch(NoSuchMethodException nsme){

  System.out.println("Erro ao carregar o metodo ClientSocketOnDisconnect");

}

}

private void notifyOnReceived(String received){

if(onReceiveMethod != null){

  Object[] args = {this, received};

  try{

    onReceiveMethod.invoke(parent, args);

  }

  catch(InvocationTargetException ite){

    ite.printStackTrace();

  }

  catch(IllegalAccessException eae){

    eae.printStackTrace();

  }

}

}

private void notifyOnSend(){

Object[] args = {null};

if(onSendMethod != null){

  try{

    onSendMethod.invoke(parent, args);

  }

  catch(InvocationTargetException ite){

    ite.printStackTrace();

  }

  catch(IllegalAccessException eae){

    eae.printStackTrace();

  }

}

}

private void notifyOnConnect(){

Object[] args = {null};

if(onConnectMethod != null){

  try{

    onConnectMethod.invoke(parent, args);

  }

  catch(InvocationTargetException ite){

    ite.printStackTrace();

  }

  catch(IllegalAccessException eae){

    eae.printStackTrace();

  }

}

}

private void notifyOnDisconnect(){

Object[] args = {null};

if(onDisconnectMethod != null){

  try{

    onDisconnectMethod.invoke(parent, args);

  }

  catch(InvocationTargetException ite){

    ite.printStackTrace();

  }

  catch(IllegalAccessException eae){

    eae.printStackTrace();

  }

}

}

/**

  • Configura os objectos de fluxo de dados utilizados na comunicação

*/

private void setStreams(){

System.out.println("Configurando os fluxos...");

try{

  write = new DataOutputStream(client.getOutputStream());

  write.flush();

  read = new DataInputStream(client.getInputStream());

  System.out.println("Fluxos configurados com sucesso");

}

catch(Exception e){

  System.out.println("Erro ao configurar os fluxos");

}

}

/**

  • Retorna true caso esteja conectado e false caso contrário

  • @return boolean isConnected

*/

public boolean isConnected(){

return running;

}

/**

  • Envia o Frame, passado como parametro, para o RemoteHost

  • @param String frame

  • @throws IOException

*/

public void send(String frame)throws IOException{

if(this.write != null){

  System.out.println("Enviando dados...");

  write.write(frame.getBytes());

  notifyOnSend();

  System.out.println("Dados enviados com sucesso");

}

}

/**

  • @param frame

  • @throws IOException

*/

public void send(byte[] frame)throws IOException{

if(this.write != null){

  System.out.println("Enviando dados...");

  write.write(frame);

  System.out.println("Dados enviados com sucesso");

}

}

/**

  • Retorna o Remote Host configurado

  • @return remoteHost

*/

public String getRemoteHost() {

return remoteHost;

}

/**

  • Configura o Remote Host

  • @param String remoteHost

*/

public void setRemoteHost(String remoteHost) {

this.remoteHost = remoteHost;

}

/**

  • Retorna o Remote Port configurado

  • @return int RemotePort

*/

public int getRemotePort() {

return remotePort;

}

/**

  • Configura o Remote Port

  • @param int remotePort

*/

public void setRemotePort(int remotePort) {

this.remotePort = remotePort;

}

}

/**

  • Thread para verificar se perdeu a conexão

  • @author Fernando Okuma

*/

class VerifyConnection implements Runnable{

ClientSocket clientSocket;

Socket socket;

public VerifyConnection(ClientSocket clientSocket){

this.clientSocket = clientSocket;

this.socket = clientSocket.client;

}

public void run(){

while(true){

  if(socket.isInputShutdown() || socket.isOutputShutdown()){

                    clientSocket.disconnect();

            }

        }

  }

}

2ª classe:

package br.com.farzac;

/**
*

  • @author zaccantte
    */
    public interface ClientSocketInterface
    {
    public void ClientSocketOnReceive(ClientSocket sender, String buffer);
    public void ClientSocketOnSend(ClientSocket sender);
    public void ClientSocketOnConnect(ClientSocket sender);
    public void ClientSocketOnDisconnect(ClientSocket sender);
    }

Desde ja, muito obrigado a quem puder me ajudar.

Olá farzac ,

Uma dica: quando for postar código, use o Code. Isso facilita a vida de quem vai ler o código. =)

Faz assim:

public class Starter{

        public static void main(String[] args) {
               ClientSocket e = new ClientSocket ();         //Cria o contexto de execução
               Thread t = new Thread(e);                        //Cria a linha de execução
               t.start();                                                 //Ativa a thread

        }

}

Espero ter ajudado…
att
[]s

que engraçado ver um codigo meu ai. rsrs

bom seguinte, para quem ainda estiver querendo saber como implementar esse treko ai…

basicamente eu usei o reflection, mas ainda tem ainda uma interface para ser usada.

fica assim:

A interface

public interface ClientSocketInterface { public void ClientSocketOnReceive(ClientSocket sender, String buffer); public void ClientSocketOnSend(ClientSocket sender); public void ClientSocketOnConnect(ClientSocket sender); public void ClientSocketOnDisconnect(ClientSocket sender); }

O main

[code]import java.io.IOException;
import java.net.ConnectException;

public class TestClientSocket implements ClientSocketInterface{

private ClientSocket clientSocket;
private StringBuffer rxBuffer = new StringBuffer();

public TestClientSocket(){
	clientSocket = new ClientSocket(this, "clientSocket", "127.0.0.1", 12001);
	try{
		clientSocket.connect(true);

		clientSocket.send("Test connection");
	}
	catch(ConnectException ce){
		System.out.println("Erro ao estabelecer a conexão");
	}
	catch(IOException ioe){
		ioe.printStackTrace();
	}
}
	
/**
 * @param args
 */
public static void main(String[] args) {
	new TestClientSocket();
}

public void ClientSocketOnConnect(ClientSocket sender) {
	System.out.println("Teste do OnConnect");
}

public void ClientSocketOnDisconnect(ClientSocket sender) {
	System.out.println("Teste do OnDisconnect");	
}

public void ClientSocketOnReceive(ClientSocket sender, String buffer) {
	rxBuffer.append(buffer);
	System.out.println(rxBuffer.toString());
	if(rxBuffer.toString().endsWith("bye")){
		clientSocket.disconnect();			
	}
}
public void ClientSocketOnSend(ClientSocket sender) {
	System.out.println("Teste do OnSend");
}

}
[/code]

o código do ClientSocket é o que está ai no primeiro post.

Sempre que ocorre algum evento, a classe ClientSocket tenta chamar o método na classe que o estanciou.

espero que ajude em alguma coisa.

flw