简体   繁体   中英

Wrong sending and receiving photos through socket

This is code of client (android application):

Socket mSocket = new Socket();
mSocket.connect(new InetSocketAddress("123.456.789.0", 50), 10000);
BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
OutputStream out = mSocket.getOutputStream();
out.write("image number 3".getBytes("UTF-8"));
out.flush();
FileInputStream mFileInputStream = new FileInputStream(mFile); // mFile - photo
while (true) {
    byte[] i3 = new byte[65536];
    int i4 = mFileInputStream.read(i3, 0, 65536);
    if (i4 < 0) {
        mFileInputStream.close();
        break;
    } else {
        out.write(i3, 0, i4);
        out.flush();
    }
}

And this code is server:

BufferedReader in = new BufferedReader(new InputStreamReader(this.in, "UTF-8"));
String i1 = in.readLine();
ByteArrayOutputStream i3 = new ByteArrayOutputStream();
while (true) {
    try {
        byte[] i4 = new byte[1024];
        int i5 = this.in.read(i4, 0, 1024);
        if (i5 < 0) {
            throw new Exception();
        } else {
            i3.write(i4, 0, i5);
            i3.flush();
        }
    } catch (Exception e1) {
        i3.close();
        break;
    }
}
BufferedImage mBufferedImage = ImageIO.read(new ByteArrayInputStream(i3.toByteArray()));

Practically 1/4 times when I trying to send photo on server and then read it with ImageIO I getting Exception:

java.lang.NullPointerException

at com.lnproduction.ru.gks.server.I1$WebClient.run(I1.java:101)

at java.lang.Thread.run(Unknown Source)

Line 101: BufferedImage mBufferedImage = ImageIO.read(new ByteArrayInputStream(i3.toByteArray())); . I also used debugger and it revealed: practically 1/4 times it sends 116K bytes, but received 113K! I really don't understand it is possible. Maybe I have some errors in my code? Help me solve it please. No ideas sorry!

You can't mix buffered and unbuffered streams on the same socket. You're losing part of the image in the buffered reader. Try using nothing but DataInputStream and DataOutputSream , and send the filename via writeUTF()/readUTF() .

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