Java - Duda Cliente/Servidor con Socket en Java

 
Vista:
Imágen de perfil de Javier
Val: 115
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Duda Cliente/Servidor con Socket en Java

Publicado por Javier (54 intervenciones) el 01/02/2018 12:57:08
Hola, tengo un ejercicio hecho en java en la que un cliente se conecta a un servidor. El cliente manda al servidor el nombre de un archivo, el servidor comprueba si existe y si existe manda el archivo al cliente, luego el cliente lo muestra por pantalla.
El ejercicio lo tengo hecho y funciona perfectamente pero he tenido mandar al cliente un booleano a true para que funcianara.
Me explico, en el código del servidor, cuando el servidor va leyendo byte a byte el archivo y mandándolo al cliente, una vez que ha mandado todos los bytes si ejecuto el programa me salta un error en el cliente de null, EOFException.
Para que no me de error y funcione perfectamente tengo que escribir en el servidor un write.boolean(true), si lo pongo a false no funciona. El caso es que no se por qué sucede esto, es decir, en el cliente no recojo un readboolean para saber si se ha mandado un true o false. Os dejo el código tanto del Servidor como del cliente para ver si veis en qué fallo o en qué no me doy cuenta. Muchas gracias

CODIGO SERVIDOR.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
 
 
/**
 *
 * @author Javier
 */
public class MandarArchivoCliente {
 
    private ServerSocket servidor = null;
    private Socket cliente = null;
    private FileReader fr = null;
    private BufferedReader br = null;
    private String rutaFichero = null;
    private DataOutputStream dos = null;
    private DataInputStream dis = null;
    private File archivo = null;
    private boolean existeFichero = false;
    private boolean archivoTerminado = false;
 
    public MandarArchivoCliente(){
 
 
        try {
            servidor = new ServerSocket(1500);
 
            cliente = servidor.accept();
 
            dis = new DataInputStream(cliente.getInputStream());
            dos = new DataOutputStream(cliente.getOutputStream());
 
            do {
 
                rutaFichero = dis.readUTF();//RECIBIMOS LA RUTA DEL FICHERO
 
                archivo = new File(rutaFichero);
 
                if(archivo.exists()) {
 
                    dos.writeBoolean(true);//MANDAMOS QUE EXISTE EL FICHERO
                    existeFichero = true;
                }else {
                    dos.writeBoolean(false);
                    existeFichero = false;
                }
 
 
 
            }while(existeFichero == false);
 
 
            //ahora deberemos de ir mandando los bytes del archivo
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(archivo));
            int leer;
 
            while((leer = bis.read()) != -1) {
 
                //archivoTerminado = false;
                dos.writeByte(leer);//Mandamos el byte del archivo
 
            }
 
            bis.close();
 
            dos.writeBoolean(true);//TENGO QUE ESCRIBIR ESTA LÍNEA PARA QUE FUNCIONE EL PROGRAMA
            servidor.close();
            cliente.close();
 
 
 
 
        } catch (IOException ex) {
 
            System.out.println(ex.getMessage());
        }
 
 
 
    }
 
 
    public static void main(String[] args) {
 
        new MandarArchivoCliente();
 
    }
 
}


CODIGO CLIENTE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 *
 * @author Javier
 */
public class RecibirArchivoServidor {
 
    private File archivo = null;
    private BufferedWriter bw = null;
    private Socket cliente = null;
    private String nombreFichero = null;
    private Scanner sca = null;
    private DataInputStream dis = null;
    private DataOutputStream dos = null;
    private boolean existeFichero = false;
    private boolean terminado = false;
 
 
    public RecibirArchivoServidor() {
 
        try {
            cliente = new Socket("localhost", 1500);
 
            dis = new DataInputStream(cliente.getInputStream());
            dos = new DataOutputStream(cliente.getOutputStream());
            sca = new Scanner(System.in);
 
 
            do {
 
                System.out.println("Escribe el nombre del fichero");
                nombreFichero = sca.nextLine();
                dos.writeUTF(nombreFichero);//MANDAMOS EL NOMBRE DEL FICHERO
 
                existeFichero = dis.readBoolean();
 
                if(!existeFichero){
                    System.out.println("EL FICHERO NO EXISTE, ESCRIBA DE NUEVO");
                }
 
 
 
            }while(existeFichero == false);
 
            File archivo = new File("ayayay.txt");
 
            archivo.createNewFile();
 
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(archivo));
 
            int lee;
 
            while((lee = dis.readByte()) != 1) {
 
                bos.write(lee);
 
            }
 
 
            bos.close();
            cliente.close();
            sca.close();
 
            BufferedReader br = new BufferedReader(new FileReader("ayayay.txt"));
 
            String linea;
 
            while((linea = br.readLine()) != null) {
                System.out.println(linea);
            }
 
 
 
 
 
        } catch (IOException ex) {
 
            System.out.println(ex.getMessage());
            System.out.println(ex.toString());        }
 
    }
 
 
    public static void main(String[] args) {
 
        new RecibirArchivoServidor();
 
    }
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de SuperIndio
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Duda Cliente/Servidor con Socket en Java

Publicado por SuperIndio (12 intervenciones) el 01/02/2018 14:57:36
Bueno yo diria que el true es = a 1
lo ultimo que envia es un 1

y del lado del cliente esta esperando un 1 para salir del while
es un valor = a 1

1
2
3
while((lee = dis.readByte()) != 1) {
                bos.write(lee);
            }
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de Javier
Val: 115
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Duda Cliente/Servidor con Socket en Java

Publicado por Javier (54 intervenciones) el 01/02/2018 15:10:31
Muchas gracias, si creo que tenga que ser eso por que otra cosa ya no veo. Creo que a lo mejor debería de haber escrito de otra forma el código.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de SuperIndio
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Duda Cliente/Servidor con Socket en Java

Publicado por SuperIndio (12 intervenciones) el 01/02/2018 16:22:18
Yo cuando envio, envio linea completa, no por byte
1
2
3
4
5
6
7
8
9
10
11
String csFPaths = csA2Imp + "/GOLDSTAR.STEP065.sysout";
File pFile = new File(csFPaths);
if ( !pFile.exists() ) {
     ExecOnInit();
}
FileReader punAuto = new FileReader(csFPaths);
BufferedReader brx = new BufferedReader(punAuto);
while ((szDato = brx.readLine()) != null) {
        System.out.println(szDato);       // out.print(szDato + "\r\n ") ;
}
punAuto.close();
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar

Duda Cliente/Servidor con Socket en Java

Publicado por Tom (1831 intervenciones) el 01/02/2018 16:55:57
Esto funciona:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class FileServer {
	ServerSocket ss;
 
	/* */
	FileServer(int port) throws IOException {
		ss = new ServerSocket(port);
	}
	/* */
	void acceptConnections() throws IOException {
		while(true) {
			Socket c = ss.accept();
			process(c);
		}
	}
	/* */
	private void process(Socket s) throws IOException {
		File fin;
		DataInputStream is = new DataInputStream(s.getInputStream());
		DataOutputStream os = new DataOutputStream(s.getOutputStream());
		String fname = is.readUTF();
 
		s.shutdownInput();
		fin = new File(fname);
		if(fin.canRead()) {
			FileInputStream fis = new FileInputStream(fin);
			byte buffer[] = new byte[1024];
			int len;
 
			os.writeLong(fin.length());
			System.out.printf("Sending file '%s' of %d bytes\n", fname, fin.length());
			while((len = fis.read(buffer)) > 0) {
				os.write(buffer, 0, len);
			}
		} else {
			os.writeLong(-1);
		}
		s.shutdownOutput(); // ensure flush
		s.close();
	}
	/* */
	public static void main(String[] args) throws IOException {
		new FileServer(8181).acceptConnections();
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class FileClient {
	/* */
	public static void main(String[] args) throws UnknownHostException, IOException {
		long size;
		int len;
		String fileToGet = new String("/etc/hosts");
		File fileToSave = new File("/tmp/hosts");
		Socket s = new Socket(InetAddress.getLocalHost(), 8181);
		DataOutputStream os = new DataOutputStream(s.getOutputStream());
		DataInputStream is = new DataInputStream(s.getInputStream());
 
		os.writeUTF(fileToGet);
		if((size = is.readLong()) >= 0) {
			FileOutputStream fos = new FileOutputStream(fileToSave);
			byte buffer[] = new byte[1024];
			while(((len = is.read(buffer)) >= 0) && (len > 0)) {
				size -= len;
				fos.write(buffer, 0, len);
			}
			fos.close();
			System.out.printf("Got new file '%s' of %d bytes\n", fileToSave.getName(), fileToSave.length());
		} else {
			System.err.printf("File '%s' does not exists in server", fileToGet);
		}
		s.close();
	}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
2
Comentar