【发布时间】:2011-11-29 04:37:43
【问题描述】:
我正在尝试通过套接字将图像从我的 android 设备发送到我的计算机。问题是我计算机上的输入流读取每个字节,但最后一组。我已经尝试修剪字节数组并发送它,我已经多次手动将-1写入输出流,但输入流从不读取-1。它只是挂起等待数据。我也尝试过不关闭流或套接字以查看是否是某种时间问题,但效果不佳。
客户端(Android 手机)
//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, 0, read);
objectOutputStream.flush();
b = new byte[socket.getSendBufferSize()];
}
//Tried manually writing -1 and flushing here
objectOutputStream.close();
is.close();
socket.close();
服务器端(计算机) 这段代码发生在对象输入流读入发送的对象之后。只有在文件开始发送时才开始读取
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, 0, read);
os.flush();
b = new byte[gSocket.getReceiveBufferSize()];
}
os.close();
即使我直接写入 -1 并刷新流,此代码也不会读入 -1。结果是 java.net.SocketException: Connection reset when the stream or socket from the android device is closed。图片几乎完全发送,但图片的最后一个像素是灰色的。我什至还尝试直接从套接字使用输出/输入流,而不是使用已经创建的 objectinputstream/objectoutputstream,但它仍然不起作用。
【问题讨论】:
-
有一点值得注意,您只需创建一次
byte[]。使用read(b)意味着您正在从偏移量 0 开始读取数组,并返回读取的字节数。后续调用只会覆盖任何先前的数据。 -
我实际上将数组重新初始化为套接字当前支持的大小。所以我不需要偏移量。
-
套接字当前支持的大小不会改变,除非你改变了它,而且无论如何为你的应用程序缓冲区使用相同的大小并没有什么特别的优势。
标签: java android sockets inputstream