简体   繁体   English

通过套接字发送和接收照片错误

[英]Wrong sending and receiving photos through socket

This is code of client (android application): 这是客户端代码(Android应用程序):

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: 当我尝试在服务器上发送照片然后使用ImageIO读取照片时,几乎有1/4倍的时间出现异常:

java.lang.NullPointerException java.lang.NullPointerException

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

at java.lang.Thread.run(Unknown Source) 在java.lang.Thread.run(未知来源)

Line 101: BufferedImage mBufferedImage = ImageIO.read(new ByteArrayInputStream(i3.toByteArray())); 第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! 我还使用了调试器,它显示了:实际上,它发送了116K字节但收到了113K的1/4倍! 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() . 尝试仅使用DataInputStreamDataOutputSream ,并通过writeUTF()/readUTF()发送文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM