0
我有一个gui,我点击一个电脑上的发送按钮和另一台电脑上的接收按钮,它发送文件。问题是我只能发送一次文件,然后我必须重新启动应用程序。java - 只能发送文件一次
它给失败的原因是这些: 发送电脑上的“套接字已关闭”,虽然我不明白为什么会这么说。接收PC上的“ArrayIndexOutOfBounds”为 。
我已经得到了这两种方法,我用来发送数据:
public void StreamIn() throws Exception { //FOR RECEIVING FILES
byte[] mybytearray = new byte[size];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVE);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
if (fos != null) fos.close();
if (bos != null) bos.close();
}
public void StreamOut() throws Exception { //FOR SENDING FILES
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (bis != null) bis.close();
if (os != null) os.close();
}
出于某种原因,OutputStream中不会写第二次,虽然我关闭并尝试发送另一个文件之前重新创建。我不明白为什么发送电脑会说插座已关闭。
感谢您的回答声明,但在这段代码什么是“缓冲”?而且,如果没有最终关闭输出流,我无法阅读。这是否也关闭了插座? – Sixtoo 2014-09-06 22:35:28
我看到它也关闭了套接字,解决方案是使用Socket.shutdownOutput() – Sixtoo 2014-09-06 22:48:12
**编辑**不是一个真正的解决方案:你不能重复使用outputstream – Sixtoo 2014-09-06 23:00:35