客户端代码(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();
}
}
这个代码是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()));
当我试图在服务器上发送照片,然后用ImageIO
读取它时,几乎有1/4次我得到异常:
java.lang.NullPointerException
com.lnproduction.ru.gks.server.I1 WebClient.run美元(I1.java: 101)
at java.lang.Thread.run(未知来源)
第101行:BufferedImage mBufferedImage = ImageIO.read(new ByteArrayInputStream(i3.toByteArray()));
。我还使用了调试器,它显示:实际上1/4次它发送116K字节,但接收113K!我真的不明白这是可能的。也许我的代码中有一些错误?请帮我解决这个问题。不知道,抱歉!
不能在同一个套接字上混合使用已缓冲和未缓冲的流。你在缓冲阅读器中丢失了部分图像。尝试只使用DataInputStream
和DataOutputSream
,并通过writeUTF()/readUTF()
发送文件名。