我试图通过一个套接字从我的Android设备发送图像到我的电脑。问题是我的计算机上的输入流会读取每一个字节,但最后一组字符。我曾尝试微调字节数组下来并发送它,我手写了-1到的OutputStream多次,但从来没有的InputStream读取-1。它只是挂起等待数据。我也试着不关闭流或插座,看看它是否是某种形式的计时问题,但没有正常工作。的InputStream没有收到EOF
客户端(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异常:当从机器人装置中的流或关闭套接字连接复位。图片几乎完全发送,但图片的最后一个像素是灰色的。我还甚至直接使用输出/输入流从插座上,而不是使用已经创建的ObjectInputStream/ObjectOutputStream的尝试,它仍然无法正常工作。
有一件事值得注意,你只需要创建一次'byte []'。使用'read(b)'意味着你从0开始读入数组,它返回读入的字节数。随后的调用只是覆盖以前的任何数据。 –
我实际上重新初始化数组以始终是套接字当前支持的大小。所以我不需要抵消。 –
套接字当前支持的大小不会改变,除非您更改它,并且对于您的应用程序缓冲区使用相同的大小没有特别的好处。 – EJP