elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


  Mostrar Temas
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16
101  Informática / Electrónica / Problema con oregano en: 5 Enero 2010, 13:50 pm
Hola a todos, em decidi a montar mi circuito, y antes de hacerlo de manera fisica, lo hice por simulación, el problema esta en que le emto una alimentacion ac de 220v y al intentar hacer la simulacion em dice que falta nodo de tierra, y es que la toma de tierra de la fuente esta vacia.

Que elemento es un nodo de tierra en oregano?

Saludos
102  Programación / Java / [SOURCE]Mini-BotNet en java (Falta arreglar una cosa) en: 5 Enero 2010, 13:19 pm
Hola a todos, os traigo una plantilla de una mini-botnet, para que podais crear una red de pc bot, para hacer multiples cosas, desde enviar todos juntos un archivo, a atender un chat irc, en resumen para hacer alguna cosa de manera masiba, o entre varios pc:

Os pongo el codigo (que tiene un fallo importante):

Servidor.java
Código
  1. /*
  2.  * Servidor.java
  3.  *
  4.  * Created on 30-dic-2009, 11:21:52
  5.  */
  6.  
  7. package main;
  8.  
  9. /**
  10.  *
  11.  * @author debci
  12.  */
  13. import java.util.logging.Level;
  14. import java.util.logging.Logger;
  15. import threads.*;
  16.  
  17. public class Servidor extends javax.swing.JFrame {
  18.  
  19.    //Instanciamos el thread que gestiona las conexiones con los bots
  20.    private static ThreadEjecución thread = new ThreadEjecución();
  21.    public static Integer cuantosBots = 0;
  22.  
  23.  
  24.  
  25.  
  26.    /** Creates new form Servidor */
  27.    public Servidor() {
  28.        initComponents();
  29.    }
  30.  
  31.    /** This method is called from within the constructor to
  32.      * initialize the form.
  33.      * WARNING: Do NOT modify this code. The content of this method is
  34.      * always regenerated by the Form Editor.
  35.      */
  36.    @SuppressWarnings("unchecked")
  37.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  38.    private void initComponents() {
  39.  
  40.        PopMenu = new javax.swing.JPopupMenu();
  41.        itemSalir = new javax.swing.JMenuItem();
  42.        jLabel1 = new javax.swing.JLabel();
  43.        numBots = new javax.swing.JLabel();
  44.        jLabel2 = new javax.swing.JLabel();
  45.        slider = new javax.swing.JSlider();
  46.        botsSel = new javax.swing.JLabel();
  47.        jLabel4 = new javax.swing.JLabel();
  48.        btnEnviar = new javax.swing.JButton();
  49.        envComando = new javax.swing.JTextField();
  50.  
  51.        itemSalir.setText("Salir");
  52.        itemSalir.setComponentPopupMenu(PopMenu);
  53.        itemSalir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
  54.        itemSalir.addActionListener(new java.awt.event.ActionListener() {
  55.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  56.                itemSalirActionPerformed(evt);
  57.            }
  58.        });
  59.        PopMenu.add(itemSalir);
  60.  
  61.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  62.  
  63.        jLabel1.setText("Tienes");
  64.  
  65.        numBots.setText("numBots");
  66.  
  67.        jLabel2.setText("bots a tu disposicion.");
  68.  
  69.        slider.setMaximum(0);
  70.        slider.setPaintLabels(true);
  71.        slider.setPaintTicks(true);
  72.        slider.setToolTipText("Sleciona cuantos bots quieres realizar para la siguiente ación.");
  73.        slider.setComponentPopupMenu(PopMenu);
  74.        slider.addChangeListener(new javax.swing.event.ChangeListener() {
  75.            public void stateChanged(javax.swing.event.ChangeEvent evt) {
  76.                sliderStateChanged(evt);
  77.            }
  78.        });
  79.  
  80.        botsSel.setText("0");
  81.  
  82.        jLabel4.setText("bots selecionados.");
  83.  
  84.        btnEnviar.setText("Enviar");
  85.  
  86.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  87.        getContentPane().setLayout(layout);
  88.        layout.setHorizontalGroup(
  89.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  90.            .addGroup(layout.createSequentialGroup()
  91.                .addContainerGap()
  92.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  93.                    .addGroup(layout.createSequentialGroup()
  94.                        .addComponent(jLabel1)
  95.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  96.                        .addComponent(numBots)
  97.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  98.                        .addComponent(jLabel2))
  99.                    .addGroup(layout.createSequentialGroup()
  100.                        .addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  101.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  102.                        .addComponent(botsSel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
  103.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  104.                        .addComponent(jLabel4)))
  105.                .addContainerGap(65, Short.MAX_VALUE))
  106.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  107.                .addContainerGap(128, Short.MAX_VALUE)
  108.                .addComponent(envComando, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
  109.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  110.                .addComponent(btnEnviar)
  111.                .addContainerGap())
  112.        );
  113.        layout.setVerticalGroup(
  114.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  115.            .addGroup(layout.createSequentialGroup()
  116.                .addGap(52, 52, 52)
  117.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  118.                    .addComponent(jLabel1)
  119.                    .addComponent(numBots)
  120.                    .addComponent(jLabel2))
  121.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  122.                    .addGroup(layout.createSequentialGroup()
  123.                        .addGap(18, 18, 18)
  124.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  125.                            .addComponent(jLabel4)
  126.                            .addComponent(botsSel)))
  127.                    .addGroup(layout.createSequentialGroup()
  128.                        .addGap(27, 27, 27)
  129.                        .addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
  130.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
  131.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  132.                    .addComponent(btnEnviar)
  133.                    .addComponent(envComando, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  134.                .addGap(63, 63, 63))
  135.        );
  136.  
  137.        slider.getAccessibleContext().setAccessibleDescription("Seleciona cuantos bots quieres realizar para la siguiente ación");
  138.  
  139.        pack();
  140.    }// </editor-fold>                        
  141.  
  142.    private void sliderStateChanged(javax.swing.event.ChangeEvent evt) {                                    
  143.        Integer valorSlider = slider.getValue();
  144.        botsSel.setText(valorSlider.toString());
  145.    }                                  
  146.  
  147.    private void itemSalirActionPerformed(java.awt.event.ActionEvent evt) {                                          
  148.        System.exit(0);
  149.    }                                        
  150.  
  151.    /**
  152.     * @param args the command line arguments
  153.     */
  154.    public static void main(String args[]) {
  155.        java.awt.EventQueue.invokeLater(new Runnable() {
  156.            @SuppressWarnings("static-access")
  157.            public void run() {
  158.                new Servidor().setVisible(true);
  159.                thread.start();
  160.  
  161.  
  162.  
  163.  
  164.  
  165.            }
  166.        });
  167.    }
  168.  
  169.    // Variables declaration - do not modify                    
  170.    private javax.swing.JPopupMenu PopMenu;
  171.    public static javax.swing.JLabel botsSel;
  172.    private javax.swing.JButton btnEnviar;
  173.    private javax.swing.JTextField envComando;
  174.    private javax.swing.JMenuItem itemSalir;
  175.    private javax.swing.JLabel jLabel1;
  176.    private javax.swing.JLabel jLabel2;
  177.    private javax.swing.JLabel jLabel4;
  178.    public static javax.swing.JLabel numBots;
  179.    public static javax.swing.JSlider slider;
  180.    // End of variables declaration                  
  181.  
  182. }
  183.  
  184.  

ControlBots.java [THREAD]
Código
  1. package threads;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.net.Socket;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import main.Servidor;
  10.  
  11.  
  12. /**
  13.  *
  14.  * @author debci
  15.  */
  16. public class ControlBots extends Thread {
  17.  
  18.    //Para leer datos en el socket
  19.    private DataInputStream dataInput;
  20.    //Para escribir datos en el socket
  21.    private DataOutputStream dataOutput;
  22.    //Cadena que envia el thread principal a cada bot
  23.    private String signal;
  24.    //Cadena de texto que el bot envia para informar
  25.    private String recivido;
  26.    //Identificador que se le asigna a cada bot
  27.    private Integer id;
  28.  
  29.    //Contador de la lista negra
  30.    public static Integer contador = 0;
  31.  
  32.    public ControlBots(Socket nuevoZombie, String envio, Integer identificador)
  33.    {
  34.        try {
  35.            dataInput = new DataInputStream(nuevoZombie.getInputStream());
  36.            dataOutput = new DataOutputStream(nuevoZombie.getOutputStream());
  37.            signal = envio;
  38.            id = identificador;
  39.  
  40.        } catch (IOException ex) {
  41.            Logger.getLogger(ControlBots.class.getName()).log(Level.SEVERE, null, ex);
  42.        }
  43.  
  44.  
  45.  
  46.    }
  47.  
  48.    public void run()
  49.    {
  50.        try {
  51.            dataOutput.writeInt(id);
  52.            dataOutput.writeUTF(signal);
  53.  
  54.  
  55.  
  56.            while (true)
  57.            {
  58.                recivido = dataInput.readUTF();
  59.  
  60.                if(recivido.equals("error"))
  61.                {
  62.                   System.out.println("Se ha producido un error.\n");
  63.                }else if(recivido.equals("todo bien"))
  64.                {
  65.                 System.out.println("Todo transcurre como deberia.\n");
  66.                }else
  67.                {
  68.                 System.out.println(recivido);
  69.                }
  70.  
  71.  
  72.  
  73.            }
  74.        } catch (IOException ex) {
  75.            System.out.println("ADIOS!");
  76.  
  77.            ThreadEjecución.listaNegra.put(contador, id);
  78.  
  79.            ThreadEjecución.RenovarDatos();
  80.            contador++;
  81.  
  82.  
  83.  
  84.        }
  85.  
  86.  
  87.  
  88.    }
  89.    public void EnviarComando(String comando)
  90.    {
  91.        try {
  92.  
  93.            dataOutput.writeUTF(comando);
  94.  
  95.        } catch (IOException ex) {
  96.            Logger.getLogger(ControlBots.class.getName()).log(Level.SEVERE, null, ex);
  97.        }
  98.    }
  99.  
  100. }
  101.  
ThreadEjecución.java [THREAD]
Código
  1. package threads;
  2.  
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.util.Hashtable;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import main.Servidor;
  10. import threads.ControlBots;
  11. /**
  12.  *
  13.  * @author debci
  14.  */
  15. public class ThreadEjecución extends Thread {
  16.    public static ServerSocket socketServidor;
  17.    public static Integer idZombie = 0;
  18.  
  19.  
  20.    public static boolean pasoTransitorio = true;
  21.    //Vector donde vamos almacenando todos los bots zombies que se van conectando
  22.    public static Hashtable<Integer, Socket> vectorZombies;
  23.  
  24.    //Vector donde vamos guardando en que indices quedan vacios
  25.    public static Hashtable<Integer, Integer> listaNegra;
  26.  
  27.    //Thread de control
  28.    public ControlBots nuevoZombie;
  29.  
  30.    //Dato donde guardamos cual hay libre
  31.    public static Integer contador = 0;
  32.  
  33.    //Comprueba que ya se haya eliminado algun bot para poner en practica la
  34.    //rutina de comprobacion.
  35.    public static boolean borrado = false;
  36.  
  37.  
  38.    public static Integer disponible = 0;
  39.  
  40.  
  41.  
  42.    public ThreadEjecución()
  43.    {
  44.        //Declaración de variables de instancia para usar durante el proceso
  45.        //Try para capturar exepciones y tratar posibles errores
  46.        try {
  47.            vectorZombies = new Hashtable();
  48.            listaNegra = new Hashtable();
  49.            socketServidor = new ServerSocket(6666);
  50.  
  51.  
  52.        } catch (IOException ex) {
  53.            Logger.getLogger(ThreadEjecución.class.getName()).log(Level.SEVERE, null, ex);
  54.        }
  55.  
  56.    }
  57.  
  58.    public void run()
  59.    {
  60.  
  61.         while (true)
  62.            {
  63.            try {
  64.  
  65.                System.out.println("Esperando conexiones...");
  66.  
  67.                Socket zombie = socketServidor.accept();
  68.                idZombie++;
  69.  
  70.  
  71.                if(listaNegra.isEmpty())
  72.                {
  73.                System.out.println("Nuevo bot añadido a la BotNet: " + idZombie + "\n");
  74.                vectorZombies.put(idZombie, zombie);
  75.                nuevoZombie = new ControlBots(zombie, "Bienvenid@ a la red de Bots!", idZombie);
  76.                }else{
  77.                    for(int i = 0; i < listaNegra.size(); i++)
  78.                    {
  79.                        if(listaNegra.containsKey(i))
  80.                        {
  81.                            disponible = i;
  82.                            break;
  83.                        }
  84.                    }
  85.                for(int i = 0; i< listaNegra.size(); i++)
  86.                {
  87.                    System.out.println("Hay disponible la clave: " + listaNegra.get(i) + ".\n");
  88.                }
  89.                System.out.println("Nuevo zombie añadido a la BotNet: " + listaNegra.get(disponible) + "\n");
  90.                vectorZombies.put(listaNegra.get(disponible), zombie);
  91.                nuevoZombie = new ControlBots(zombie, "Bienvenid@ a la red zombie!",listaNegra.get(disponible));
  92.                System.out.println("La clave " + listaNegra.get(disponible) + " ya no esta disponible.\n");
  93.                listaNegra.remove(disponible);
  94.  
  95.                ControlBots.contador--;
  96.  
  97.                }
  98.  
  99.  
  100.  
  101.  
  102.                nuevoZombie.start();
  103.                Servidor.slider.setMaximum(idZombie);
  104.                Servidor.numBots.setText(idZombie.toString());
  105.                borrado = false;
  106.  
  107.  
  108.            } catch (IOException ex) {
  109.                Logger.getLogger(ThreadEjecución.class.getName()).log(Level.SEVERE, null, ex);
  110.            }
  111.  
  112.  
  113.            }
  114.    }
  115. public static void RenovarDatos()
  116. {
  117.    idZombie--;
  118.  
  119.  
  120.            Servidor.slider.setValue(idZombie);
  121.            Servidor.slider.setMaximum(idZombie);
  122.            Servidor.numBots.setText(idZombie.toString());
  123.  
  124. }
  125.  
  126. public void rutinaComprovacion()
  127. {
  128.  
  129. }
  130.  
  131. public void enviarComando(int cuantos, String comando)
  132. {
  133.  
  134.  
  135.  
  136. }
  137. }
  138.  

Un ejemplo de cliente


Vamos a hacer un cliente de echo:

Código
  1. package main;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.net.Socket;
  7. import java.net.UnknownHostException;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10.  
  11. /**
  12.  *
  13.  * @author debci
  14.  */
  15. public class Cliente {
  16. public static Socket socketCliente;
  17. public static DataInputStream dis;
  18. public static DataOutputStream dos;
  19. public static String cadenaEnviar;
  20. public static int identificador;
  21.    public static void main(String args[])
  22.    {
  23.        try {
  24.  
  25.            socketCliente = new Socket("localhost", 6666);
  26.            dis = new DataInputStream(socketCliente.getInputStream());
  27.            dos = new DataOutputStream(socketCliente.getOutputStream());
  28.            ThreadBot hilo = new ThreadBot();
  29.            hilo.start();
  30.  
  31.        } catch (UnknownHostException ex) {
  32.            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
  33.        } catch (IOException ex) {
  34.            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
  35.        }
  36.    }
  37.  
  38.    static class ThreadBot extends Thread {
  39.  
  40.  
  41.    public void run()
  42.    {
  43.            try {
  44.                identificador = dis.readInt();
  45.                System.out.println("Soy el bot numero " + identificador + ".\n");
  46.                while (true) {
  47.                    try {
  48.                        String recivido = dis.readUTF();
  49.                        System.out.println(recivido);
  50.                        dos.writeUTF(recivido);
  51.                    } catch (IOException ex) {
  52.                        Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
  53.                    }
  54.                }
  55.            } catch (IOException ex) {
  56.                Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
  57.            }
  58.    }
  59.  
  60. }
  61. }
Podemos usar esta plantilla para hacer todo tipo de cosas, ojo ninguna que esta fuera del limite de lo legal, lo prohibo explicitamente, y no me haré responsable de los posibles daños que pueda acarrear.

El uso es simple solo hace falta saber algo de java, programasmo unc liente y el servidor le envia datos (strings, integers, booleans...) y el cliente responde, todo esto ademas se hace masificado.

No es funcional por si solo, haria falta añadrile parte de codigo.

Ahora el problema que tengo:

Cuando un nuevo bot se añade, se le asigna un id, y cuando se elimina se añade esa id a una lista donde luego cuando otro entre se le asignara para tener todos los id ocupados, de esta manera cuando uno s eva al siguiente se le asigan el id del que se ha ido.

Pero el problema reside, en que cuando se desconectan dos simultaneos, luego no funciona como deberia, al siguiente le asigan bien el id pero al otro ya no.

Estoy desesperador lelvo como 3 semanas con esto y no salgo de este problema, seguro que es una tonteria, pero no soy capaz de ver donde etsa fallando.


Espero que os guste.


Saludos a tod@s
103  Programación / Java / Problema lógico... [Otro mas..] (pero que cabezota que soy...) en: 30 Diciembre 2009, 15:39 pm
Hola a todos, estoy depurando mi aplicacion de red... una tool util que pronto pondre en forma de source y binario en el foro.

Es una aplicacion cliente-servidor que usa sockets, threads y demas...

Bueno uso un sistema de enumeración para ordenarlos en la memoria y poder identificarlos.

La cosa esta en lo siguiente:

Cuando un cliente se conecta al servidor:

Añado 1 al contador (contador++;)

Cuando se desconecta, disminuyo 1 (contador--;)

Pero ocurre el siguiente fallo:

Si abro dos, les doy como id 1 y 2.

Si se va uno, disminuyo y el contador esta en 1 (contador - 1 = 2) y si entra otro se le asigna el 2, ahora tengo dos con el el identificador 2, y uno se remplaza al otro en la tabla de hash.

Me planteé hacerlo que nunca disminuya, pero ocurre el siguiente fallo, cuando quiero hacer un cast a todos, las id que se han desconectado pero sin embargo todavia estan registradas ya no tiene un objeto guardado y produce expeciones cosa mala.

Que puedo hacer?


Saludos
104  Seguridad Informática / Materiales y equipos / La tarjeta de mis sueños :P en: 29 Diciembre 2009, 18:34 pm
Hola a tod@s, queria preguntar sobre que tarjeta de red comprarme (me refiero a los sticks usb que tan de moda se han puetso) con la que pueda snifar red, hacer juegos con ettercap y auditar seguridad wep de mi red.

Tengo una hercules con driver rt73usb y de entrada no puedo usar el ettercap, no funciona bien con aircrack...

Algun modelo en concreto? La mas fiable, la mas conocida en este mundillo.

Saludos
105  Programación / Java / Abrir conexion con sitio web en: 28 Diciembre 2009, 15:57 pm
Hola a tod@s, esta vez queria preguntaros sobre como crear una conexion con un sitio web, supongo que debe ser con sockets, la realidad es que quiero provocar un dos en mi propio servidor (o intentarlo) y investigando he llegado a la conclusion de que se puede hacer con envio de paquetes de red.

Como se podria hacer esto en java?

Son fines meramente equitativos e instructivos, para comprobar la seguridad de mi apache ante tal tipo de ataques, que ultimamente andan extendiendose por la red.

Saludos a tod@s
106  Seguridad Informática / Hacking / Problema con Ettercap, no me detecta ningun host :s en: 28 Diciembre 2009, 13:26 pm
Hola a tod@s, esta tarde me puse a investigar con el ettercap para intentar hacer un mitm a mi propio pc (uno que tengo en lan) y ver si de verdad funciona.
El problema, es que cuando le doy a "Scan for host" no me encuentra ninguno dice noseque de mask 255 y no me encuentra ninguno, da pena ver como una herramienta tan potente se rompe en el punto mas sencillo y en teoria menos problematico.

Alguien sabe porque ocurre esto?


Saludos
107  Programación / Java / Error tonto con threads y sockets en: 26 Diciembre 2009, 15:39 pm
Hola a todos jeje, soy yo otra vez, he vuelto al java xD
Mirad estoy constryendo una aplicacion con sockets, que gestiona varios cliente mediante el uso de threads, la cosa esta en que cada vez que se conecta un cliente al servidor, este le abre un thread, y lo deja en ejecucion hasta que el cliente se cierra y le envia un binario, cuando le envia el binario se cumple el bucle y el thread muere, pero ocurre una cosa extraña, mirad el codigo:

ClienteGui.java
Código
  1.  
  2. package sockets;
  3.  
  4. import java.io.DataInputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.Socket;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12.  
  13. /**
  14.  *
  15.  * @author debci
  16.  */
  17. public class ClienteGui extends javax.swing.JFrame {
  18.            public static Socket socket;
  19.            public static InputStream is;
  20.            public static OutputStream os;
  21.            public static DataInputStream dis;
  22.            public static DataOutputStream dos;
  23.    /** Creates new form ClienteGui */
  24.    public ClienteGui() {
  25.        initComponents();
  26.    }
  27.  
  28.    /** This method is called from within the constructor to
  29.      * initialize the form.
  30.      * WARNING: Do NOT modify this code. The content of this method is
  31.      * always regenerated by the Form Editor.
  32.      */
  33.    @SuppressWarnings("unchecked")
  34.    // <editor-fold defaultstate="collapsed" desc="Generated Code">
  35.    private void initComponents() {
  36.  
  37.        jButton1 = new javax.swing.JButton();
  38.        jScrollPane1 = new javax.swing.JScrollPane();
  39.        textoEnv = new javax.swing.JTextArea();
  40.  
  41.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  42.        addWindowListener(new java.awt.event.WindowAdapter() {
  43.            public void windowClosed(java.awt.event.WindowEvent evt) {
  44.                formWindowClosed(evt);
  45.            }
  46.            public void windowClosing(java.awt.event.WindowEvent evt) {
  47.                formWindowClosing(evt);
  48.            }
  49.        });
  50.  
  51.        jButton1.setText("Enviar");
  52.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  53.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  54.                jButton1ActionPerformed(evt);
  55.            }
  56.        });
  57.  
  58.        textoEnv.setColumns(20);
  59.        textoEnv.setRows(5);
  60.        jScrollPane1.setViewportView(textoEnv);
  61.  
  62.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  63.        getContentPane().setLayout(layout);
  64.        layout.setHorizontalGroup(
  65.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  66.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  67.                .addContainerGap(337, Short.MAX_VALUE)
  68.                .addComponent(jButton1)
  69.                .addContainerGap())
  70.            .addGroup(layout.createSequentialGroup()
  71.                .addGap(21, 21, 21)
  72.                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  73.                .addContainerGap(117, Short.MAX_VALUE))
  74.        );
  75.        layout.setVerticalGroup(
  76.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  77.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  78.                .addContainerGap(89, Short.MAX_VALUE)
  79.                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  80.                .addGap(83, 83, 83)
  81.                .addComponent(jButton1)
  82.                .addContainerGap())
  83.        );
  84.  
  85.        pack();
  86.    }// </editor-fold>
  87.  
  88.    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  89.        try {
  90.            String cadena = textoEnv.getText();
  91.            dos.writeBoolean(true);
  92.            dos.writeUTF(cadena);
  93.  
  94.        } catch (IOException ex) {
  95.            Logger.getLogger(ClienteGui.class.getName()).log(Level.SEVERE, null, ex);
  96.        }
  97.    }
  98.  
  99.    private void formWindowClosed(java.awt.event.WindowEvent evt) {
  100.  
  101.    }
  102.  
  103.    private void formWindowClosing(java.awt.event.WindowEvent evt) {
  104.        try {
  105.            dos.writeBoolean(false);
  106.        } catch (IOException ex) {
  107.            Logger.getLogger(ClienteGui.class.getName()).log(Level.SEVERE, null, ex);
  108.        }
  109.    }
  110.  
  111.    /**
  112.     * @param args the command line arguments
  113.     */
  114.    public static void main(String args[]) {
  115.        java.awt.EventQueue.invokeLater(new Runnable() {
  116.            public void run() {
  117.                try {
  118.                    new ClienteGui().setVisible(true);
  119.                    socket = new Socket("localhost", 5557);
  120.                    is = socket.getInputStream();
  121.                    os = socket.getOutputStream();
  122.                    dis = new DataInputStream(is);
  123.                    dos = new DataOutputStream(os);
  124.                } catch (IOException ex) {
  125.                    Logger.getLogger(ClienteGui.class.getName()).log(Level.SEVERE, null, ex);
  126.                }
  127.            }
  128.        });
  129.    }
  130.  
  131.    // Variables declaration - do not modify
  132.    private javax.swing.JButton jButton1;
  133.    private javax.swing.JScrollPane jScrollPane1;
  134.    private javax.swing.JTextArea textoEnv;
  135.    // End of variables declaration
  136.  
  137. }
  138.  
  139.  


Servidor.java

Código
  1. package sockets;
  2.  
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import threads.ThreadServidor;
  7.  
  8. /**
  9.  *
  10.  * @author debci
  11.  */
  12. public class Servidor {
  13.  
  14.    public static void main(String[] args) throws IOException {
  15.      Servidor servidor = new Servidor();
  16.      servidor.ServidorChat();
  17.  
  18.    }
  19.  
  20.   public void ServidorChat()
  21.    {
  22.        try
  23.        {
  24.            ServerSocket socketServidor = new ServerSocket(5557);
  25.  
  26.            while (true)
  27.            {
  28.                System.out.println("Esperando conexiones...");
  29.                Socket cliente = socketServidor.accept();
  30.  
  31.                Runnable nuevoCliente = new ThreadServidor(cliente);
  32.                Thread hilo = new Thread(nuevoCliente);
  33.                hilo.start();
  34.  
  35.            }
  36.        } catch (Exception e)
  37.        {
  38.            e.printStackTrace();
  39.        }
  40.    }
  41. }
  42.  
  43.  
  44.  

ThreadServidor.java
Código
  1. package threads;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.net.Socket;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9.  
  10. /**
  11.  *
  12.  * @author debci
  13.  */
  14. public class ThreadServidor extends Thread {
  15.  
  16. //Socket al que esta conectado el cliente
  17.    private Socket socket1;
  18.  
  19. /** Para lectura de datos en el socket */
  20.    private DataInputStream dataInput;
  21.  
  22.    /** Para escritura de datos en el socket */
  23.    private DataOutputStream dataOutput;
  24.  
  25.    private boolean acabado = true;
  26.  
  27.  
  28.    public ThreadServidor(Socket socket) {
  29.        try {
  30.            socket1 = socket;
  31.            dataInput = new DataInputStream(socket.getInputStream());
  32.            dataOutput = new DataOutputStream(socket.getOutputStream());
  33.  
  34.        } catch (IOException ex) {
  35.  
  36.            System.err.println("Error de procesamiento de datos: \n" + ex);
  37.  
  38.        }
  39.    }
  40.  
  41.    public void run() {
  42.        try {
  43.          while(acabado){
  44.            acabado = dataInput.readBoolean();
  45.            String mensajeRecivido = dataInput.readUTF();
  46.            System.out.println(mensajeRecivido + "\n");
  47.  
  48.          }
  49.  
  50.        } catch (IOException ex) {
  51.            Logger.getLogger(ThreadServidor.class.getName()).log(Level.SEVERE, null, ex);
  52.        }
  53.  

Me explico, la cosa esta en que cuando el cliente, se cierra (formClosing) se envia el booleano al thread que lo esta atendiendo.
Si el booleano se cambia, se rompe el bucle while y se muere el thread.

El problema, y no se de donde viene, es que cuando cierro un cliente y le pido desconexion y que mate al thread, el servidor libera un error:

Código:
26-dic-2009 15:30:55 threads.ThreadServidor run
GRAVE: null
java.io.EOFException
        at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
        at java.io.DataInputStream.readUTF(DataInputStream.java:572)
        at java.io.DataInputStream.readUTF(DataInputStream.java:547)
        at threads.ThreadServidor.run(ThreadServidor.java:50)
        at java.lang.Thread.run(Thread.java:619)
Me da ese error y luego continua atendiendo clientes, cada vez que cierro un cliente me lo da, y no se porque es, y como comprendereis no quiero darle uso a una aplicacon que tiene un defecto claro.

Saludos y gracias a todos.
108  Informática / Electrónica / [Iniciación] Que pic escojer? en: 17 Diciembre 2009, 18:42 pm
Hola a todos, estoy entrando en el mundo de la electronica, y me gustaria saber por que pic empezar, ya tengo idea de circuitos electronicos y electricos (diodos, transistores, leds...) y me gustaria adquirir algun pic sencillito, programable en c o otro que no fuese asm (me mata xD).
Y el proceso de como se carga un programa en un pic, porque los que eh estado mirando no tienen ningun sitio donde meterselo, como implanto mi codigo en un pic? Si me diesen los detalles completos, os lo agradeceria ^^ asi como algun modelo en cocnreto barato y que tenga documentacion, no pido que sea muy potente, ram sencillita y una eeprom sencillita tambien.

Saludos a todos
109  Programación / Java / Problema lógico con bucle en: 30 Noviembre 2009, 21:56 pm
 :¬¬
Hola a todos llevo toda la santa tarde rompiendome la cabeza delante del monitor, para sacar una tonteria  :xD:¬¬ ).

Mirad el codigo:
Código
  1. /**
  2.  *
  3.  * @author debci
  4.  */
  5. public class Encriptador {
  6.  
  7. private static int numeroCaracteres;
  8.    private static int ncClave;
  9.    private String sCadenaInvertida;
  10.  
  11. public void cifra() {
  12. String cadenaIntroducida = new String("Hola");
  13. String Clave = new String("debci");
  14. String Subcadena = Clave.substring(Clave.length() / 2 + 1);
  15.  
  16. sCadenaInvertida = "";
  17. cadenaIntroducida = cadenaIntroducida.toLowerCase();
  18. char[] matrizCaracteres = cadenaIntroducida.toCharArray();
  19.  
  20. char[] matrizCharMovida  = Clave.toCharArray();
  21. numeroCaracteres = matrizCaracteres.length;
  22. int y = 0;
  23. for(int i = 0; i < numeroCaracteres; i++) {
  24.    if (i == numeroCaracteres - 2 ) {
  25.      y = 0;
  26.    }
  27.    y = i + 1;
  28.    matrizCaracteres[y] = matrizCharMovida[i];
  29.  
  30. }
  31.  
Intento conseguir que se mezclen la dos strings de la siguiente manera:
Palabra 1 -> Hola
Palabra 2 -> debci

Y que quede helci
Es decir que coja una letra de cada uno, pero no lo consigo....


En teoria mi bucle lógico tendria que hacerlo pero no hay manera.

Estoy frustrado  :(
 :rolleyes:
 :rolleyes:
 :rolleyes:
 :rolleyes:

Ayudenme por favor  :-[

Saludos  :P
110  Programación / Java / Duda Planes malvados en: 30 Noviembre 2009, 19:47 pm
Juas Juas que malo soy xD
Queria haceros una pregunta.
Como prodria modificar desde java un sector de memoria directamente, que no sea un archivo, como por ejemplo, el primer byte de un disco duro...
¬¬
Ya me entendeis, leer offsets y direciones de memoria (offsets, segmentos...) desde java.
Cuando digo leer digo escribir..

¬¬

Saludos
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines