3 java sockets android inputstream
我试图通过套接字从我的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();
Run Code Online (Sandbox Code Playgroud)
服务器端(计算机)这段代码发生在对象输入流读入发送的对象之后.它只在文件开始发送时才开始读取
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();
Run Code Online (Sandbox Code Playgroud)
即使我直接写入-1并刷新流,此代码也从不读入-1.结果是java.net.SocketException:当Android设备的流或套接字关闭时连接重置.图片几乎完全发送,但图片的最后一个像素是灰色的.我甚至尝试直接从套接字使用out/input流,而不是使用已经创建的objectinputstream/objectoutputstream,它仍然无法正常工作.
首先,我认为你误解了EOF(-1)的含义.这并不意味着服务器写了-1,这意味着服务器关闭了流.
我认为你的主要问题是服务器和客户端都在循环读取,并且都没有达到关闭流的程度.他们陷入僵局 - 两人都在等待另一人先关闭.


如果您知道没有更多数据要写,那么只需关闭流即可.
| 归档时间: |
|
| 查看次数: |
3802 次 |
| 最近记录: |