I read most of SO answers and couldn't find why readUTF()
hangs. The code is so generic, but this somehow hangs.
Client side:
int ip = "192.168.56.101"
String filepath = "your local file path" // pdf file works, mp3 or mp4 don't work
int port = 6000;
int port1 = 6001;
Socket socket = new Socket(ip, port);
Socket socket1 = new Socket(ip, port1);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
String filename = "filename_doesnt_matter_but_file_type_matters";
dos.writeUTF(filename); // USED writeUTF()
dos.flush(); dos.close(); socket.close();
FileInputStream fis = new FileInputStream(new File(filepath));
BufferedInputStream bis = new BufferedInputStream(fis);
final byte[] bytearray = new byte[(int) fis.length()];
bis.read(bytearray, 0, bytearray.length);
oos.writeObject(bytearray); // THIS WRITES THE FILE
oos.flush(); oos.close(); socket1.close();
Server side:
int port = 6000;
int port1 = 6001;
ServerSocket ss = new ServerSocket(port);
ServerSocket ss1 = new ServerSocket(port1);
Socket socket = ss.accept();
Socket socket1 = ss1.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
FileOutputStream fos = new FileOutputStream(new File("local path where I save my file"));
ois = new ObjectInputStream(socket1.getInputStream());
final BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytearray = (byte[]) ois.readObject();
bos.write(bytearray);
bos.flush();
String filename = dis.readUTF(); <----- HANGS HERE
Filename is very small that size is not an issue. What could be a possible problem?
Edit: Forgot to mention that this reads filename "Dummy1.pdf" but doesn't read something like "mp4" or "file_dummy.mp3" I still have no idea when it can read and when it hangs...
I tried ObjectOutputStream
instead of DataOutputStream
and tried writeObject(filename)
as well, but it still doesn't read. I also tried wrapping BufferedInputStream
as suggested, which didn't work as well...
NEW EDIT: I figured out when it hangs. It hangs when I try to transfer an mp3 or mp4 file. When I transfer a pdf file, the filename of the file is transferred. However, when I try to transfer an audio or a video file, the file is transferred but the filename is not (code hangs at readUTF()
. If I comment it out, then I receive the file)..