Os pongo el codigo (que tiene un fallo importante):
Servidor.java
Código
/*
* Servidor.java
*
* Created on 30-dic-2009, 11:21:52
*/
package main;
/**
*
* @author debci
*/
import java.util.logging.Level;
import java.util.logging.Logger;
import threads.*;
public class Servidor extends javax.swing.JFrame {
//Instanciamos el thread que gestiona las conexiones con los bots
private static ThreadEjecución thread = new ThreadEjecución();
public static Integer cuantosBots = 0;
/** Creates new form Servidor */
public Servidor() {
initComponents();
}
/** 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() {
PopMenu = new javax.swing.JPopupMenu();
itemSalir = new javax.swing.JMenuItem();
jLabel1 = new javax.swing.JLabel();
numBots = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
slider = new javax.swing.JSlider();
botsSel = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
btnEnviar = new javax.swing.JButton();
envComando = new javax.swing.JTextField();
itemSalir.setText("Salir");
itemSalir.setComponentPopupMenu(PopMenu);
itemSalir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
itemSalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
itemSalirActionPerformed(evt);
}
});
PopMenu.add(itemSalir);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Tienes");
numBots.setText("numBots");
jLabel2.setText("bots a tu disposicion.");
slider.setMaximum(0);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setToolTipText("Sleciona cuantos bots quieres realizar para la siguiente ación.");
slider.setComponentPopupMenu(PopMenu);
slider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
sliderStateChanged(evt);
}
});
botsSel.setText("0");
jLabel4.setText("bots selecionados.");
btnEnviar.setText("Enviar");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numBots)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botsSel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)))
.addContainerGap(65, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(128, Short.MAX_VALUE)
.addComponent(envComando, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnEnviar)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(numBots)
.addComponent(jLabel2))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(botsSel)))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnEnviar)
.addComponent(envComando, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(63, 63, 63))
);
slider.getAccessibleContext().setAccessibleDescription("Seleciona cuantos bots quieres realizar para la siguiente ación");
pack();
}// </editor-fold>
private void sliderStateChanged(javax.swing.event.ChangeEvent evt) {
Integer valorSlider = slider.getValue();
botsSel.setText(valorSlider.toString());
}
private void itemSalirActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@SuppressWarnings("static-access")
public void run() {
new Servidor().setVisible(true);
thread.start();
}
});
}
// Variables declaration - do not modify
private javax.swing.JPopupMenu PopMenu;
public static javax.swing.JLabel botsSel;
private javax.swing.JButton btnEnviar;
private javax.swing.JTextField envComando;
private javax.swing.JMenuItem itemSalir;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
public static javax.swing.JLabel numBots;
public static javax.swing.JSlider slider;
// End of variables declaration
}
ControlBots.java [THREAD]
Código
package threads;ThreadEjecución.java [THREAD]
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.Servidor;
/**
*
* @author debci
*/
public class ControlBots extends Thread {
//Para leer datos en el socket
private DataInputStream dataInput;
//Para escribir datos en el socket
private DataOutputStream dataOutput;
//Cadena que envia el thread principal a cada bot
private String signal;
//Cadena de texto que el bot envia para informar
private String recivido;
//Identificador que se le asigna a cada bot
private Integer id;
//Contador de la lista negra
public static Integer contador = 0;
public ControlBots(Socket nuevoZombie, String envio, Integer identificador)
{
try {
dataInput = new DataInputStream(nuevoZombie.getInputStream());
dataOutput = new DataOutputStream(nuevoZombie.getOutputStream());
signal = envio;
id = identificador;
} catch (IOException ex) {
Logger.getLogger(ControlBots.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run()
{
try {
dataOutput.writeInt(id);
dataOutput.writeUTF(signal);
while (true)
{
recivido = dataInput.readUTF();
if(recivido.equals("error"))
{
System.out.println("Se ha producido un error.\n");
}else if(recivido.equals("todo bien"))
{
System.out.println("Todo transcurre como deberia.\n");
}else
{
System.out.println(recivido);
}
}
} catch (IOException ex) {
System.out.println("ADIOS!");
ThreadEjecución.listaNegra.put(contador, id);
ThreadEjecución.RenovarDatos();
contador++;
}
}
public void EnviarComando(String comando)
{
try {
dataOutput.writeUTF(comando);
} catch (IOException ex) {
Logger.getLogger(ControlBots.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Código
package threads;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.Servidor;
import threads.ControlBots;
/**
*
* @author debci
*/
public class ThreadEjecución extends Thread {
public static ServerSocket socketServidor;
public static Integer idZombie = 0;
public static boolean pasoTransitorio = true;
//Vector donde vamos almacenando todos los bots zombies que se van conectando
public static Hashtable<Integer, Socket> vectorZombies;
//Vector donde vamos guardando en que indices quedan vacios
public static Hashtable<Integer, Integer> listaNegra;
//Thread de control
public ControlBots nuevoZombie;
//Dato donde guardamos cual hay libre
public static Integer contador = 0;
//Comprueba que ya se haya eliminado algun bot para poner en practica la
//rutina de comprobacion.
public static boolean borrado = false;
public static Integer disponible = 0;
public ThreadEjecución()
{
//Declaración de variables de instancia para usar durante el proceso
//Try para capturar exepciones y tratar posibles errores
try {
vectorZombies = new Hashtable();
listaNegra = new Hashtable();
socketServidor = new ServerSocket(6666);
} catch (IOException ex) {
Logger.getLogger(ThreadEjecución.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run()
{
while (true)
{
try {
System.out.println("Esperando conexiones...");
Socket zombie = socketServidor.accept();
idZombie++;
if(listaNegra.isEmpty())
{
System.out.println("Nuevo bot añadido a la BotNet: " + idZombie + "\n");
vectorZombies.put(idZombie, zombie);
nuevoZombie = new ControlBots(zombie, "Bienvenid@ a la red de Bots!", idZombie);
}else{
for(int i = 0; i < listaNegra.size(); i++)
{
if(listaNegra.containsKey(i))
{
disponible = i;
break;
}
}
for(int i = 0; i< listaNegra.size(); i++)
{
System.out.println("Hay disponible la clave: " + listaNegra.get(i) + ".\n");
}
System.out.println("Nuevo zombie añadido a la BotNet: " + listaNegra.get(disponible) + "\n");
vectorZombies.put(listaNegra.get(disponible), zombie);
nuevoZombie = new ControlBots(zombie, "Bienvenid@ a la red zombie!",listaNegra.get(disponible));
System.out.println("La clave " + listaNegra.get(disponible) + " ya no esta disponible.\n");
listaNegra.remove(disponible);
ControlBots.contador--;
}
nuevoZombie.start();
Servidor.slider.setMaximum(idZombie);
Servidor.numBots.setText(idZombie.toString());
borrado = false;
} catch (IOException ex) {
Logger.getLogger(ThreadEjecución.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void RenovarDatos()
{
idZombie--;
Servidor.slider.setValue(idZombie);
Servidor.slider.setMaximum(idZombie);
Servidor.numBots.setText(idZombie.toString());
}
public void rutinaComprovacion()
{
}
public void enviarComando(int cuantos, String comando)
{
}
}
Un ejemplo de cliente
Vamos a hacer un cliente de echo:
Código
package main;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.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author debci
*/
public class Cliente {
public static Socket socketCliente;
public static DataInputStream dis;
public static DataOutputStream dos;
public static String cadenaEnviar;
public static int identificador;
public static void main(String args[])
{
try {
socketCliente = new Socket("localhost", 6666);
dis = new DataInputStream(socketCliente.getInputStream());
dos = new DataOutputStream(socketCliente.getOutputStream());
ThreadBot hilo = new ThreadBot();
hilo.start();
} catch (UnknownHostException ex) {
Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
static class ThreadBot extends Thread {
public void run()
{
try {
identificador = dis.readInt();
System.out.println("Soy el bot numero " + identificador + ".\n");
while (true) {
try {
String recivido = dis.readUTF();
System.out.println(recivido);
dos.writeUTF(recivido);
} catch (IOException ex) {
Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
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










Autor





En línea



tambien podrias aplicarle el Look and fell del sisema













que te lio 