-4

When I run the client, it returns(an error): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at java.io.BufferedOutputStream.write(Unknown Source) at Sockets.FileSocketClient.main(FileSocketClient.java:14)

I understand where it is occurring[bos.write(mybytearray, 0, bytesRead);], I just don't understand WHY

Server

import java.io.*;  
import java.net.*;

public class FileSocketServer {

public static void main(String args[]) throws IOException {
    ServerSocket serverSocket = new ServerSocket(1235);
    File myFile = new File("test.txt");

    while(true) {
        Socket socket = serverSocket.accept(); //Understand 
        byte[] mybytearray = new byte[(int)myFile.length()]; //Don't understand
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile)); //Don't understand
        bis.read(mybytearray, 0, mybytearray.length); //Don't understand
        OutputStream os = socket.getOutputStream(); //Don't understand
        os.write(mybytearray, 0, mybytearray.length); //Don't understand
        os.flush(); //Don't understand
        socket.close(); //Don't understand
    }
}

}

Client

package Sockets;

import java.io.*;
import java.net.*;

public class FileSocketClient {
public static void main(String args[]) throws IOException{
    Socket socket = new Socket("GANNON-PC", 1235); //Understand
    byte[] mybytearray = new byte[1024]; //Don't understand
    InputStream is = socket.getInputStream(); //Don't understand
    FileOutputStream fos = new FileOutputStream("mods//test.txt"); //Don't understand
    BufferedOutputStream bos = new BufferedOutputStream(fos); //Don't understand
    int bytesRead = is.read(mybytearray, 0, mybytearray.length); //Don't understand
    bos.write(mybytearray, 0, bytesRead); //Don't understand
    bos.close(); //
    socket.close();
}
}
n1ghtk1n9
  • 3
  • 7
  • I guess you would have saved time by commenting what you understood instead. In any case this code requires you to know how streams work in Java and roughly how TCP works from a developer point of view (sockets, connections and whatever). Otherwise it's impossible to explain what this code does. – Jack Jul 25 '13 at 02:25
  • SO is **NOT** a site where you say I don't understand any of the following, please explain... – Steve P. Jul 25 '13 at 02:25
  • The error is to do with `bos.write(mybytearray, 0, bytesRead);` – lewisjb Jul 25 '13 at 02:27
  • @Jack I DO understand roughly how TCP works(at least in my opinion), I know how to send text/strings between two connections. – n1ghtk1n9 Jul 25 '13 at 02:38

1 Answers1

0

The proper way to send a file:

public void sendFile(Socket socket, File myFile) throws IOException  {
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); //get the output stream of the socket
    dos.writeInt((int) myFile.length()); //write in the length of the file

    InputStream in = new FileInputStream(myFile); //create an inputstream from the file
    OutputStream out = socket.getOutputStream(); //get output stream
    byte[] buf = new byte[8192]; //create buffer
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len); //write buffer
    }
    in.close(); //clean up
    out.close();
}

Receive a file:

public void receiveFile(Socket socket, String fileName) throws IOException {
        DataInputStream dis = new DataInputStream(socket.getInputStream()); //get the socket's input stream
        int size = dis.readInt(); //get the size of the file.
        InputStream in = socket.getInputStream(); 
        OutputStream out = new FileOutputStream(fileName); //stream to write out file
        int totalBytesRead = 0;
        byte[] buf = new byte[8192]; //buffer
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len); //write buffer
        }

        out.close(); //clean up
        in.close();
}

The difference between this code and yours is first I send over the length of the file before I send the entire file. The file might be bigger than the buffer you have allocated for it, so you need a loop to read it incrementally.

nook
  • 2,378
  • 5
  • 34
  • 54
  • Your sending code is correct, your receiving code not. The receiving code should be exactly the same as the sending code, with the inputs and outputs reversed. Your receiving code doesn't detect EOS at the correct time and will therefore suffer from the same problem as the OP, and it miscounts totalBytesRead as well. If you're closing the socket after sending the file there is no need to send the length first at all. Close, but no cigar. – EJP 7 mins ago – user207421 Jul 25 '13 at 06:55
  • @EJP Ahh you're right. Fixed it. – nook Jul 25 '13 at 17:58
  • @publ1c_stat1c Thanks for the answer, but I have one question. If I wanted the server to send the file and the client to receive the file, what would I put as the argument 'socket' for `sendFile(socket, fileName)`? I was thinking putting my `ServerSocket` object there, but it says it has to be a socket, not a serversocket(which I can clearly see) – n1ghtk1n9 Jul 26 '13 at 00:39
  • @pub1c_stat1c If it's not too much to ask, could you give an example on how to use this or explain it some more? I don't fully understand how I would use it. Since it's a boolean type, should I use it in like an `if` or `while` statement? Or use is like a `void` method? – n1ghtk1n9 Jul 26 '13 at 00:48
  • @n1ghtk1n9 When you `.accept()` from a serversocket the object returned is a socket. Use that to communicate. I will clean up the code a bit to help you. – nook Jul 26 '13 at 07:29
  • publ1c_stat1c What is 8192? – David Doria Oct 03 '13 at 15:11
  • @publ1c_stat1c Also, if the number of bytes received is less than the size of the buffer, won't it not write anything? – David Doria Oct 03 '13 at 15:30
  • @DavidDoria Your first question: http://stackoverflow.com/a/1111689/1431238. And to your second question, give it a try and find out. – nook Oct 03 '13 at 18:55
  • @publ1c_stat1c Ok, I found out that .read() returns the final set of bytes that it reads and then returns -1 the next time (i.e. only returns -1 if it read 0 bytes because there were none left to read!). – David Doria Oct 03 '13 at 19:04