sampat nayak sampat nayak - 1 month ago 17
Java Question

Error while sending the two files over the socket

I am trying to send two files over the socket, but unfortunately I am getting error:


Java.io.EOFException


I am posting the server side and client side code. Please help me to send the two files over the socket.

ServerSocket servsock = null; /* initilization */
Socket sock = null;
//Socket sock = null;
try {
System.out.println("waiting please connect the device");
servsock = new ServerSocket(5555); /* port number */
sock=servsock.accept();
System.out.println("waiting...");

BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
DataInputStream dis = new DataInputStream(bis);

/* read the length of the file */
long fileLength = dis.readLong();
fos = new FileOutputStream(FILE_TO_RECEIVED1);
bos = new BufferedOutputStream(fos);

for(int j = 0; j < fileLength; j++)
bos.write(bis.read());
bos.close();
/* once the first file is read , I have closed the BOS */

/* code to read the second file */
long fileLength1 = dis.readLong();
fos = new FileOutputStream(FILE_TO_RECEIVED2);/* path where
second file should be stored */
bos = new BufferedOutputStream(fos);
/* read the second file */
for(int j = 0; j < fileLength1; j++)
bos.write(bis.read());

bos.close();
dis.close();


GUI side code
//code to send the two files over the socket

BufferedOutputStream bos = new
BufferedOutputStream(sock.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
System.out.println("Accepted connection : " + sock);

File myFile1 = new File (FILE_TO_SEND1);
long length = myFile1.length();
dos.writeLong(length); //sending length of the file

fis = new FileInputStream(myFile1);
bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1) bos.write(theByte);
/*sending first file */
bis.close();
fis.close();
dos.close();

dos = new DataOutputStream(bos);

File myFile2 = new File (FILE_TO_SEND2);
long length1 = myFile2.length();
dos.writeLong(length);

fis = new FileInputStream(myFile1);
bis = new BufferedInputStream(fis);
int theByte1 = 0;
/*sending second file */

while((theByte = bis.read()) != -1) bos.write(theByte);
bis.close();

Answer

on the GUI side code you are sending two files But during sending the second file

 fis = new FileInputStream(myFile1);

you have made fileinputstream to myFIle1 on both the times , change it to myFile2 on the second time

Comments