java – 没有接收EOF的InputStream
发布时间:2020-12-15 04:55:48 所属栏目:Java 来源:网络整理
导读:我试图通过套接字从我的 Android设备发送图像到我的电脑.问题是我的计算机上的输入流读取每个字节但最后一组.我已经尝试修剪字节数组并发送它,我已经多次手动将-1写入输出流,但输入流从不读取-1.它只是挂起等待数据.我也尝试不关闭流或套接字,看看它是否是某
我试图通过套接字从我的
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,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,read); os.flush(); b = new byte[gSocket.getReceiveBufferSize()]; } os.close(); 即使我直接写入-1并刷新流,此代码也从不读入-1.结果是java.net.SocketException:当Android设备的流或套接字关闭时连接重置.图片几乎完全发送,但图片的最后一个像素是灰色的.我甚至尝试直接从套接字使用out / input流,而不是使用已经创建的objectinputstream / objectoutputstream,它仍然无法正常工作. 解决方法
首先,我认为你误解了EOF(-1)的含义.这并不意味着服务器写了-1,这意味着服务器关闭了流.
我认为你的主要问题是服务器和客户端都在循环读取,并且都没有达到关闭流的程度.他们陷入僵局 – 两人都在等待另一人先关闭. 你的客户: 你的服务器: 如果您知道没有更多数据要写,那么只需关闭流即可. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |