Ver Mensaje Individual
  #1 (permalink)  
Antiguo 11/07/2011, 14:11
deitynitros98
 
Fecha de Ingreso: junio-2010
Mensajes: 132
Antigüedad: 13 años, 11 meses
Puntos: 3
Mulples clietes en servidor de java

Hola me encuentro usando sockets y serversockets, ahora quiero un servidor que acepte multples clientes...lo que hice fue lo siguiente, utilice un hilo por cada cliente que se conecta a mi servidor, pero estos hilos no logran funcionar, aki les dejo la clase hilocliente y el cliente como tal, presentan problemas de retardo, por favor necesito ayuda urgentemenete

Código:
package agenteinteligente;

/**
 *
 * @author Jose
 */


import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Cliente_Agente extends javax.swing.JFrame implements KeyListener,Runnable{

    /** Creates new form Cliente_Agente */

    private ObjectOutputStream salida;
    private ObjectInputStream entrada;
    private Socket cliente;
    private int salidaInt;
    private String mensaje,direccionServer;
    private boolean conectado;
    private Thread t;

    public Cliente_Agente(String Direccion) {
        initComponents();
        this.addKeyListener(this);

        salidaInt = 0;
        mensaje = "";
        direccionServer = Direccion;
        conectado = false;
        t = new Thread(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    public void run()
    {
        conectarAServidor(direccionServer);
        obtenerFlujos();
        while(true)
        {
            System.out.println("Paso");
            this.enviarDatos(salidaInt);
            try{Thread.sleep(2000);}catch(Exception e){}
        }
    }

    public void ejecutarCliente()
    {
        try{
            //conectarAServidor(direccionServer);
            //obtenerFlujos();
            //procesarConexion();
            conectado = true;
            t.start();


        }catch(Exception e){}
    }
    
    private void conectarAServidor(String direccion)
    {
        try{
            cliente = new Socket(direccion,12345);
        
        }catch(Exception e){}

        System.out.println("Agente Conectado");
        
    }
    
    private void obtenerFlujos()
    {
        //System.out.println("Se recibieron los flujos");
        try{
        this.salida = new ObjectOutputStream(cliente.getOutputStream());
        this.salida.flush();
        this.entrada = new ObjectInputStream(cliente.getInputStream());
        System.out.println("Se recibieron los flujos");
        
        }
        catch(IOException e)
        {
            System.out.println("Exception en Obtener flujos");
        }  
    }
    
    private void procesarConexion()
    {
        do{
            
            try{

                salidaInt =  entrada.readInt();
            }
            //catch(ClassNotFoundException e){System.out.println("ProcesarConexion");}
            catch(IOException e){System.out.println("ProcesarConexion");}
   
        }while(conectado);
    }

    private void enviarDatos(int movimiento)
    {
        if(true)
        try{

            salida.writeInt(movimiento);
            salida.flush();
            System.out.println(movimiento + " enviado");

        }
        catch(Exception e){System.out.println("Excepcion en la funcion enviarDatos");}

        else
            System.out.println("No hay conexion");
    }

   private void closeConnection()
   {
      System.out.println("Cerrando Conexion");

      try {
         salida.close();
         entrada.close();
         cliente.close();
      }
      catch( IOException ioException ) {
         ioException.printStackTrace();
      }

      System.out.println("\nConexion Cerrada");
   }

    public void keyPressed(KeyEvent ke)
    {
        int key = ke.getKeyCode();

        switch(key)
        {
            case KeyEvent.VK_LEFT:
                enviarDatos(4);
                System.out.println("Izquierda");
                salidaInt = 4;
                break;
            case KeyEvent.VK_RIGHT:
                enviarDatos(6);
                System.out.println("derecha");
                salidaInt = 6;
                break;
            case KeyEvent.VK_UP:
                enviarDatos(8);
                System.out.println("arriba");
                salidaInt = 8;
                break;

            case KeyEvent.VK_DOWN:
                enviarDatos(2);
                System.out.println("abajo");
                salidaInt = 2;
                break;

            case KeyEvent.VK_ESCAPE:
                System.out.println("Chao!!");
                closeConnection();
                conectado = false;
        }
    }

    public void keyReleased(KeyEvent ke) {}
    public void keyTyped(KeyEvent ke){}
    

    /**
    * @param args the command line arguments
    */
    /*public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Cliente_Agente().setVisible(true);
            }
        });
    }*/

    // Variables declaration - do not modify                     
    // End of variables declaration                   

}
su respectivo main

Código:
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Cliente_Agente cliente;
        //cliente = new Cliente_Agente();

         if ( args.length == 0 )
         cliente = new Cliente_Agente( "127.0.0.1");
       else
         cliente = new Cliente_Agente( args[ 0 ] );


        cliente.setVisible(true);
        cliente.ejecutarCliente();
    }

}

gracias de antemano