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?