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

时间:2016-11-05 19:12:14

标签: java android

这是客户端代码(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();
    }
}

这段代码是服务器:

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()));

当我尝试在服务器上发送照片然后使用ImageIO阅读时,实际上是1/4倍我得到了例外:

  

显示java.lang.NullPointerException

     

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

     

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

第101行:BufferedImage mBufferedImage = ImageIO.read(new ByteArrayInputStream(i3.toByteArray()));。我也使用了调试器,它显示:几乎是发送116K字节的1/4,但收到了113K!我真的不明白这是可能的。也许我的代码中有一些错误?请帮我解决一下。没有想法抱歉!

1 个答案:

答案 0 :(得分:0)

您不能在同一个套接字上混用缓冲和非缓冲流。您在缓冲的阅读器中丢失了部分图像。请尝试使用DataInputStreamDataOutputSream,并通过writeUTF()/readUTF()发送文件名。