在套接字上发送和接收文件

我正在从java服务器向远程Android客户端发送文件。 我使用outputstream写字节。 在读取这些字节时,read()方法在流结束后继续尝试读取字节。 如果我在服务器端关闭输出流,则读取操作工作罚款。 但我必须再次在同一个套接字上写文件,所以无法关闭输出流的任何解决方案?

注意:我的代码适用于共享单个文件

编写文件的代码

public static void writefile(String IP, String filepath, int port, OutputStream out ) throws IOException { ByteFileConversion bfc = new ByteFileConversion(); byte[] file = bfc.FileToByteConversion(filepath); out.write(file, 0, file.length); out.close(); // i donot want to close this and how can I tell reading side that stream is ended. System.out.println("WRITTEN"); } 

我在Android上阅读文件:

  public Bitmap fileReceived(InputStream is) { Bitmap bitmap = null; String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); String fileName = "a.png"; String imageInSD = baseDir + File.separator + fileName; // System.out.println(imageInSD); if (is!= null) { FileOutputStream fos = null; OutputStream bos = null; try { bos = new FileOutputStream(imageInSD); byte[] aByte = new byte[1024]; int bytesRead; int index = 0; DataInputStream dis = new DataInputStream(is); while ( (bytesRead = is.read(aByte)) >0 ) { index = bytesRead +index; bos.write(aByte, 0, bytesRead); // index = index+ bytesRead; System.out.println("Loop"+aByte+ " byte read are "+bytesRead+ "whree index ="+ index); } bos.flush(); bos.close(); Log.i("IMSERVICE", "out of loop"); java.io.FileInputStream in = new FileInputStream(imageInSD); bitmap = BitmapFactory.decodeStream(in); bitmap = BitmapFactory.decodeFile(imageInSD); Log.i("IMSERVICE", "saved"); // if (bitmap != null) // System.out.println("bitmap is "+ bitmap.toString()); } catch (IOException ex) { // Do exception handling // Log.i("IMSERVICE", "exception "); System.out.println("ex"); } } return bitmap; } 

其实我想重置套接字连接

提前致谢

你需要:

  1. 在文件前发送文件的长度。 您可以使用DataOutputStream.writeLong()和接收器上的DataInputStream.readLong()
  2. 在接收器处准确读取流中的许多字节:

     while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0) { out.write(buffer, 0, count); total += count; } 

E&OE

其实我想重置套接字连接

其实你不想做任何这样的事情。

如果我不关闭输出流,那么另一侧的读取操作会继续读取

这是因为客户端套接字的InputStream仍在等待服务器发送一些数据包,从而阻塞主线程。

解:

您可以将每个发送( OutputStream )和读取( InputStream )数据包从套接字放入线程,以防止在读取和发送时阻塞主线程。

创建一个读取InputStream的线程和另一个用于OutputStream的线程

边注:

不要试图关闭你的outputStream它不能再次重新打开,因为文档说:

关闭返回的OutputStream将关闭关联的套接字。

close的一般合同是它关闭输出流。 封闭流无法执行输出操作,无法重新打开。