List a directory in Java using sockets (client / server)

0

I am starting to use sockets in Java and it seems that I still do not fully understand them. I am trying to create a server that waits in a port for a client to connect to it and that when the client connects, it sends a list of a directory.

The code that I have been testing so far without much success is the following:

Server:

import java.io.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Servidor {

    public static void main(String args[]){
        ServerSocket servidor;
        Socket socket;
        try{
            servidor=new ServerSocket(5005);
            while(true){
                socket=servidor.accept();
                System.out.println("Ha llegado un cliente");
                OutputStream flujoSalida=socket.getOutputStream();
                DataOutputStream dos=new DataOutputStream(flujoSalida);

                InputStream flujoEntrada=socket.getInputStream();
                DataInputStream dis=new DataInputStream(flujoEntrada);
                //Lectura y listado del directorio
                String sDirectorio = "./";
                File f = new File(sDirectorio);
                File[] ficheros = f.listFiles();
                for (int x=0;x<ficheros.length;x++){
                  dos.writeUTF(ficheros[x].getName());
                }
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}

Customer

import java.io.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Cliente {
    public static void main(String args[]){
       InetAddress direccion;
        Socket servidor;
        try{
           direccion=InetAddress.getByName("127.0.0.1");
           servidor=new Socket(direccion,5005);
           DataInputStream datos=new DataInputStream(servidor.getInputStream());
           String mensaje=datos.readLine();
           System.out.println(mensaje);
           servidor.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}

I can not get the server to send a list of files from a directory to the client.

Could someone light up my path a bit?

    
asked by Hechi 09.12.2016 в 21:03
source

2 answers

5

You have the problem on the server:

 while(true){
     servidor=new ServerSocket(5005); <- Aqui esta el error
     socket=servidor.accept();
     ...
 }
  

Address already in use: JVM_Bind

When creating the server within while with new ServerSocket(5005) after accepting a client recreates an instance of ServerSocket with an existing port.

EDITED

For your example to work, you must change in Customer :

String mensaje=datos.readLine();

Because of this:

String ficheros = datos.readUTF();

Now let's see how you are listing the files:

You Server

String sDirectorio = "./";
File f = new File(sDirectorio);
File[] ficheros = f.listFiles();
for (int x=0;x<ficheros.length;x++){
     dos.writeUTF(ficheros[x].getName());
}

Every run on the dos.writeUTF(ficheros[x].getName()) server you need in the client datos.readUTF() to read the content.

The question is do we know the number of files that a directory will contain? So we do not know how many datos.readUTF(); we should place in the client. For this I can think of 2 solutions:

1 - Solution:
Server

String sDirectorio = "./";
String listadoFicheros = "";
File f = new File(sDirectorio);
File[] ficheros = f.listFiles();

for (int x=0;x<ficheros.length;x++){
     if(listadoFicheros.equals("")) {
        listadoFicheros = ficheros[x].getName();
     } else {
        listadoFicheros = listadoFicheros + ";" + ficheros[x].getName();
     }

 }
 dos.writeUTF(listadoFicheros);//<- "directorio1;directorio2;directorio3"

Customer

String ficheros = datos.readUTF();
System.out.println(ficheros);//Listado de ficheros
String files[] = ficheros.split(";");//Separamos el string con ";"
for (int i = 0; i < files.length; i++) {
      System.out.println(i+" "+files[i]);
}

The advantages of sending information like this is that we only send the server to the client, the bad thing is that we must treat the information when sending and receiving.

2 - A solution closer to your approach.

Server

String sDirectorio = "./";
File f = new File(sDirectorio);
File[] ficheros = f.listFiles();
dos.writeUTF(String.valueOf(ficheros.length));//Numero de elementos
for (int x=0;x<ficheros.length;x++){                  
     dos.writeUTF(ficheros[x].getName());
}

Customer

int numeroFicheros = Integer.parseInt(datos.readUTF());

for (int i = 0; i < numeroFicheros; i++) {
      System.out.println(datos.readUTF());
}

The advantage of doing it this way is that we do not treat the information, and the disadvantage is that we make several shipments per socket.

    
answered by 09.12.2016 / 22:47
source
-1
Address already in use: JVM_Bind

It means that some other application is already listening in the port the current application is trying to bind.

what you have to do is either the port for your current application or better to finish discovering the application that is already running and kill it.

In Linux you can find the pid application by:

netstat -tulpn
    
answered by 09.12.2016 в 23:44