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

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Socket java Servidor Cliente
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Socket java Servidor Cliente  (Leído 4,152 veces)
momo1234

Desconectado Desconectado

Mensajes: 5


Ver Perfil
Socket java Servidor Cliente
« 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.


En línea

RyogiShiki


Desconectado Desconectado

Mensajes: 745


げんしけん - Hikkikomori FTW!!!


Ver Perfil WWW
Re: Socket java Servidor Cliente
« Respuesta #1 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


En línea

momo1234

Desconectado Desconectado

Mensajes: 5


Ver Perfil
Re: Socket java Servidor Cliente
« Respuesta #2 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.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Aplicacion cliente-servidor en JAVA
Java
rex 5 21,377 Último mensaje 28 Septiembre 2004, 12:01 pm
por rex
cliente/servidor socket « 1 2 »
Programación Visual Basic
mig5ueles 11 4,656 Último mensaje 22 Enero 2007, 20:47 pm
por mig5ueles
Socket / cliente servidor
Java
danielo- 4 14,181 Último mensaje 2 Octubre 2009, 23:19 pm
por Debci
Socket C++ cliente/servidor con ip de internet: no me va
Programación C/C++
ellentejilla 1 3,768 Último mensaje 27 Octubre 2010, 21:22 pm
por Horricreu
socket cliente y servidor c++ / linux
Programación C/C++
d00ze13 0 4,689 Último mensaje 28 Abril 2011, 18:38 pm
por d00ze13
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines