Java – InputStream that does not receive EOF

I tried to send an image from my Android device to my computer through a socket The problem is that the input stream on my computer reads each byte, but the last group I've tried to trim the byte array and send it. I've manually written - 1 to the output stream many times, but the input stream never reads - 1 It just hangs waiting for data I also tried not to close the stream or socket to see if it was some kind of timing problem, but it didn't work

Client (Android phone)

//This has to be an objectoutput stream because I write objects to it first
InputStream is = An image's input stream android
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(object);
objectOutputStream.flush();

byte[] b = new byte[socket.getSendBufferSize()];
int read = 0;
while ((read = is.read(b)) != -1) {
   objectOutputStream.write(b,read);
   objectOutputStream.flush();
   b = new byte[socket.getSendBufferSize()];
}
//Tried manually writing -1 and flushing here
objectOutputStream.close();
is.close();
socket.close();

Server side (computer) this code occurs after the object input stream reads the sent object It starts reading only when the file starts sending

File loc = Location of where the file is stored on the computer
loc.createNewFile();
FileOutputStream os = new FileOutputStream(loc);
Socket gSocket = The socket
ObjectInputStream gInputStream = Object Input stream created from the sockets input stream already used to read in the prevIoUs objects

byte[] b = new byte[gSocket.getReceiveBufferSize()];
int read = 0;
while ((read = gInputStream.read(b)) != -1) {
   os.write(b,read);
   os.flush();
   b = new byte[gSocket.getReceiveBufferSize()];
}

os.close();

Even if I write - 1 directly and brush the new stream, this code never reads - 1 The result is Java net. Socketexception: the connection is reset when the stream or socket of the Android device is closed The picture is almost completely sent, but the last pixel of the picture is gray I even tried to use the out / input stream directly from the socket instead of the created objectinputstream / objectoutputstream, and it still didn't work properly

Solution

First of all, I think you misunderstood the meaning of EOF (- 1) This does not mean that the server wrote - 1, it means that the server closed the stream

I think your main problem is that both the server and the client are reading circularly, and neither of them has closed the flow They are deadlocked - both are waiting for the other to close first

Your client:

Your server:

If you know there is no more data to write, just close the stream

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>