sampat nayak sampat nayak - 9 months ago 65
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:

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 */

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++)
/* 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++)


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

BufferedOutputStream bos = new
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 = != -1) bos.write(theByte);
/*sending first file */

dos = new DataOutputStream(bos);

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

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

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

Answer Source

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