简体   繁体   中英

Java - sending a file over socket - file isn't received fully

i am really stuck with a little project i'm doing. I am trying to send music files (only .wav) over a socket from a server to a client. Everything works perfectly fine (i think...) except that the file that is received by the client isn't complete. I can't play the file and I can see that it is a bit smaller than the one the server has. What am I doing not right?

Here is the server code:

    private Socket client;
private String filename;
private TBMCAudioServer ac;

private FileInputStream fis;
private BufferedOutputStream out;

int bufferSize = 0;

FileSender(Socket client, String filename, TBMCAudioServer ac){

    this.client = client;
    this.filename = filename;
    this.ac = ac;
}

@Override
public void run(){

    ac.ex.sendMessage(client, "[#preload#]" + filename);

    File dir = new File(ac.getDataFolder() + File.separator + "music");
    if(!dir.exists()){
        dir.mkdir();
    }

    File file = new File(dir, filename + ".wav");

    long length = file.length();
    if(length > Integer.MAX_VALUE){
        logger.info("File is too large.");
    }
    byte[] bytes = new byte[(int) length];

    try{
        fis = new FileInputStream(file);
        out = new BufferedOutputStream(client.getOutputStream());
    } catch (IOException e){
        logger.info(e.getMessage());
    }

    int count;

    try {
        while((count = fis.read(bytes,0,bytes.length)) != -1){
            out.write(bytes, 0, count);
        }

        out.flush();
        out.close();
        fis.close();
    } catch (IOException e) {
        logger.info(e.getMessage());
    }

}

and here you can see my client code:

    private Socket server;
private String filename;
private AudioClient ac;

InputStream is = null;
FileOutputStream fos = null;
int bufferSize = 0;

FileReceiver(Socket server, String filename, AudioClient ac){
    this.server = server;
    this.filename = filename;
    this.ac = ac;
}

@Override
public void run() {

    try{
        is = server.getInputStream();

        bufferSize = server.getReceiveBufferSize();
        ac.logConsole("Buffer size: " + bufferSize);
    } catch (IOException ex){
        ac.logConsole(ex.getMessage());
    }

    try{
        fos = new FileOutputStream(AudioClient.util.getLineValue(3) + filename + ".wav");
    } catch (FileNotFoundException e){
        ac.logConsole(e.getMessage());
    }

    byte[] bytes = new byte[bufferSize];

    int count;

    try {
        while((count = is.read(bytes, 0, bytes.length)) != -1){
            fos.write(bytes, 0, count);
        }

        ac.logConsole("yay");
        is.close();
        fos.flush();
        fos.close();
    } catch (IOException e) {
        ac.logConsole(e.getMessage());
    }
}

Okay I managed to send the file fully so I can see it has the same size as where it came from with my new code. The only problem is that i'm sending a music file and I can't play the file that is sent. Maybe someone knows what the problem is?

Server code:

package me.Ciaran.simplefileserver;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleFileServer {

public final static int SOCKET_PORT = 13267;  // you may change this
public final static String FILE_TO_SEND = "D:/server/plugins/TBMCAudioServer/music/DLTALL.wav";  // you may change this

public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
  servsock = new ServerSocket(SOCKET_PORT);
  while (true) {
    System.out.println("Waiting...");
    try {
      sock = servsock.accept();
      System.out.println("Accepted connection : " + sock);
      // send file

      final File myFile= new File(FILE_TO_SEND); //sdcard/DCIM.JPG
      byte[] mybytearray = new byte[8192];
      fis = new FileInputStream(myFile);  
      bis = new BufferedInputStream(fis);
      DataInputStream dis = new DataInputStream(bis);
      try {
          os = sock.getOutputStream();
          DataOutputStream dos = new DataOutputStream(os);
          dos.writeUTF(myFile.getName());     
          dos.writeLong(mybytearray.length);
          int read;
          while((read = dis.read(mybytearray)) != -1){
              dos.write(mybytearray, 0, read);
          }

      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }

      System.out.println("Done.");
    }
    finally {
      if (bis != null) bis.close();
      if (os != null) os.close();
      if (sock!=null) sock.close();
    }
  }
}
finally {
  if (servsock != null) servsock.close();
}
}
}

and here is the client code:

package me.Ciaran.simplefileclient;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SimpleFileClient {

public final static int SOCKET_PORT = 13267;      // you may change this
public final static String SERVER = "127.0.0.1";  // localhost
public final static String
   FILE_TO_RECEIVED = "C:/Users/Ciaran/Documents/TESTEN/music/DLTALL.wav";  // you may change this, I give a
                                                        // different name because i don't want to
                                                        // overwrite the one used by server...

  public final static int FILE_SIZE = 6022386; // file size temporary hard coded
                                           // should bigger than the file to be downloaded

public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
  sock = new Socket(SERVER, SOCKET_PORT);
  System.out.println("Connecting...");

  // receive file

  InputStream in;
  int bufferSize=0;

  try {
      bufferSize=sock.getReceiveBufferSize();
      in=sock.getInputStream();
      DataInputStream clientData = new DataInputStream(in);
      String fileName = clientData.readUTF();
      System.out.println(fileName);
      OutputStream output = new FileOutputStream(FILE_TO_RECEIVED);
      byte[] buffer = new byte[bufferSize];
      int read;
      while((read = clientData.read(buffer)) != -1){
          output.write(buffer, 0, read);
      }

  } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }

  System.out.println("File " + FILE_TO_RECEIVED
      + " downloaded (" + current + " bytes read)");
}
finally {
  if (fos != null) fos.close();
  if (bos != null) bos.close();
  if (sock != null) sock.close();
}
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM