Fabix123
Fabix123

Reputation: 1

Java Socket Message isn't readable after file tranfer

I sent a File from one Socket to an other. After this I try to sent a simple message but this doesn't work. Can someone tell why?

Sent File and Message:

byte[] buffer = new byte[16384];
InputStream inputStream = new FileInputStream(f);
OutputStream outputStream = client.getOutputStream();
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, len);
}
client.shutdownOutput();

//Following doesnt work:
PrintWriter m_out = new PrintWriter(outputStream);
m_out.println("anfrage erhalten");
m_out.flush();

Receive File and Message:

File pdfFile = new File("marke.pdf");
OutputStream fs = new FileOutputStream(pdfFile);

OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();

byte[] buffer = new byte[16384];
int len = 0;
while ((len = is.read(buffer)) != -1) {
    fs.write(buffer, 0, len);
}   
fs.flush();
fs.close();
client.shutdownOutput();

// Here i will receive the Message after the file transfer, but this doesnt work!
System.out.println(br.readLine());

Upvotes: 0

Views: 145

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

You're writing a message toy the output stream after having shut down the output. You should get an IOException by doing it.

Moreover, you're using the same stream to write textual data after having written some binary data. If you do this, you have to find a way at the other side to know where the binary data ends, and when the textual data begins. If you read bytes until the end of the stream like you're doing, you will read the binary data concatenated with the bytes of the textual data.

Upvotes: 2

Related Questions