Foro de elhacker.net

Programación => Java => Mensaje iniciado por: momo1234 en 12 Mayo 2012, 13:40 pm



Título: Socket java Servidor Cliente
Publicado por: momo1234 en 12 Mayo 2012, 13:40 pm
hola todos tengo un problema con mi servidor es cuando hay uno cliente conectado con el servidor todo funciona bien , pero cuando llege otro cliente me puedo conectar con el servidor pero no puedo enviar archivos como si el servidor se bloquea gracias todos aqui esta el codigo de mi servidor

Servidor

Código:



import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Servidor
    implements Runnable
{

    ServerSocket server;
    Socket connection;
    DataOutputStream output;
    BufferedInputStream bis;
    BufferedOutputStream bos;
    byte receivedData[];
    int in;
    String file;
    String file1;
    String file2;



    public Servidor()
    {
        connection = null;
        try
        {
            server = new ServerSocket(1234);
            System.out.println("serveur");
        }
        catch(Exception e)
        {
            System.out.println((new StringBuilder("erreur serveurn")).append(e).toString());
            System.exit(1);
        }
    }

    public void run()
    {
        Socket client = null;
        do
        {
            do
            {
                if(server == null)
                {
                    return;
                }
                try
                {
                    client = server.accept();
                    System.out.println("nuevo cliente");
                }
                catch(IOException e)
                {
                    System.err.println((new StringBuilder("connexion impossible")).append(e.getMessage()).toString());
                }
            } while(server == null);
            try
            {
                InputStream in = client.getInputStream();
                DataInputStream dis = new DataInputStream(client.getInputStream());
                file = dis.readUTF();
                file1 = dis.readUTF();
                file2=dis.readUTF();
                int i=dis.readInt();
                if(i==1)
                {

               File directorio = new File("c:\\directorio\\"+file1+"\\"+file2+"\\");
                directorio.mkdir();
                }
                if(file != null)
                {
                  bos = new BufferedOutputStream(new FileOutputStream("C:\\directorio\\"+file1+"\\"+file2+"\\"+ file));
                    byte buf[] = new byte[1024];
                    int len;
                    while((len = in.read(buf)) > 0)
                    {
                        bos.write(buf, 0, len);
                    }
                  //  in.close();
                    bos.close();
                }
            }
            catch(IOException e)
            {
                System.out.println((new StringBuilder("Error: ")).append(e).toString());
            }
        } while(true);
    }

    public static void main(String a[])
    {
        Servidor servidor = new Servidor();
        (new Thread(servidor)).start();
    }
}



gracias  todos.


Título: Re: Socket java Servidor Cliente
Publicado por: RyogiShiki en 12 Mayo 2012, 14:35 pm
Para aceptar múltiples conexiones a un Server e interactuar con diferentes clientes debes hacerlo utilizando threads, aquí tienes algunos ejemplos:

http://www.kieser.net/linux/java_server.html
http://biese.wordpress.com/2009/06/14/how-to-create-a-simple-java-socket-thread-server/

Y tener bastante cuidado si en algún momento realizas una Blocking Call que podría bloquear el programa mientras se realiza la tarea deseada.

Espero sea de ayuda.

Saludos


Título: Re: Socket java Servidor Cliente
Publicado por: momo1234 en 12 Mayo 2012, 16:57 pm
hola gracias por tu ayuda he hecho este servidor multithread pero tengo un problema cuando hay un cliente que esta conectado todo funciona bien pero cuando se conecta otro cliente los ficheros no llegen aqui esta el codigo gracias.

MultiThreadedServer

Código:


public class MultiThreadedServer implements Runnable{

    protected int          serverPort   = 1234;
    protected ServerSocket serverSocket = null;
    protected boolean      isStopped    = false;
    protected Thread       runningThread= null;

    public MultiThreadedServer(int port){
        this.serverPort = port;
    }

    public void run(){
        synchronized(this){
            this.runningThread = Thread.currentThread();
        }
        openServerSocket();
        while(! isStopped()){
            Socket clientSocket = null;
            try {
                clientSocket = this.serverSocket.accept();
            } catch (IOException e) {
                if(isStopped()) {
                    System.out.println("Server Stopped.") ;
                    return;
                }
                throw new RuntimeException(
                    "Error accepting client connection", e);
            }
            new Thread(
                new WorkerRunnable(
                    clientSocket, "Multithreaded Server", null, null, null)
            ).start();
        }
        System.out.println("Server Stopped.") ;
    }


    private synchronized boolean isStopped() {
        return this.isStopped;
    }

    public synchronized void stop(){
        this.isStopped = true;
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }
    }

    private void openServerSocket() {
        try {
            this.serverSocket = new ServerSocket(this.serverPort);
        } catch (IOException e) {
            throw new RuntimeException("Cannot open port 8080", e);
        }
    }
    public static void main(String...args) throws IOException
    {
    MultiThreadedServer server = new MultiThreadedServer(1234);
    new Thread(server).start();

    try {
        Thread.sleep(20 * 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Stopping Server");
    // server.stop();
    }
}

WorkerRunnable

Código:

public class WorkerRunnable implements Runnable{

    protected Socket clientSocket = null;
    protected String serverText   = null;

    public WorkerRunnable(Socket clientSocket, String serverText,  String file , String file1,  String file2 ) {
        this.clientSocket = clientSocket;
        this.serverText   = serverText;
    }

    public void run() {
        try {
        InputStream in =clientSocket.getInputStream();
             DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
             String file = dis.readUTF();
             String file1 = dis.readUTF();
             String file2 = dis.readUTF();
             int i=dis.readInt();
             if(i==1)
             {

             File directorio = new File("c:\\direccion\\"+file1+"\\"+file2+"\\");
             directorio.mkdirs();
             }
             if(file != null)
             {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\direccion\\"+file1+"\\"+file2+"\\"+ file));
                 byte buf[] = new byte[1024];
                 int len;
                 while((len = in.read(buf)) > 0)
                 {
                     bos.write(buf, 0, len);
                 }
               in.close();
               bos.close();
             }
         
        } catch (IOException e) {
            //report exception somewhere.
            e.printStackTrace();
        }
    }
}



Gracias todos.