I am writing a program to transfer files between two computers, but I am not closing the socket for I am using the same socket to transfer other messages (like transfer server's folders organization).
At a certain point, I have this code to transfer files from server to client:
Server
System.out.println("Sending " + threadItem.second.getName() + " of " + threadItem.second.length() + "b");
FileInputStream fileInputStream = new FileInputStream(threadItem.second);
byte[] buffer = new byte[BLOCK_SIZE];
int count;
while ((count = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
outputStream.write(END_OF_STREAM, 0, 1);
System.out.println("File sent.");
fileInputStream.close();
And the client receives:
FileOutputStream fOutputStream = new FileOutputStream(new File("./received/" + obj.toString()));
byte[] buffer = new byte[4096];
int count;
while ((count = dataInputStream.read(buffer)) > 0 && !(buffer[count - 1] == '\0')) {
fOutputStream.write(buffer, 0, count);
}
fOutputStream.close();
It works, but the real problem is when I send another message from server to client instants after this situation above :
Server
outputStream.writeUT(new JSONObject()
.put("command", MessageHandler.ConnectionMessage.OVER.toString())
.toString());
And the client receives using:
JSONObject jsonObject = new JSONObject(dataInputStream.readUTF());
But, at this line above I get :
SEVERE: null
java.io.UTFDataFormatException: malformed input around byte 1
at java.io.DataInputStream.readUTF(DataInputStream.java:656)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at labrpc.secondquestion.Client.lambda$jButton3ActionPerformed$1(Client.java:499)
at java.lang.Thread.run(Thread.java:748)
Somehow write
corrupted the writeUTF
or something like that (I've been searching for everything related to it and found nothing relevant), I've tried to remove the write
from server just to test and these error doesn't appeared, but it's an important routine.
My question is : Does the write and writeUTF are mutually exclusive in socket communication?
Thanks in advance.