如何在不关闭输出流的情况下连续发送和接收数据



我正在制作应用程序,该应用使用Hotspot Server和Client Connection在两个设备之间使用WiFi传输数据。

我正在使用以下代码将数据从客户端发送到服务器。

OutputStream stream = socket.getOutputStream();
                    stream.write("".getBytes());
                    ContentResolver cr = context.getContentResolver();

                    InputStream is = null;
                    try {
                        is = new ByteArrayInputStream(data.getBytes());
                    } catch (Exception e) {
                        Log.d("TEST", e.toString());
                    }
                    copyFile(is, stream);

是我的复制文件方法。

  public static boolean copyFile(InputStream inputStream, OutputStream out) {
            byte[] buf = new byte[1024];
            while (true) {
                try {
                    int len = inputStream.read(buf);
                    if (len != -1) {
                        out.write(buf, 0, len);
                    } else {
                        //out.flush();
//out.close();

                        return true;
                    }
                } catch (IOException e) {
                    Log.d("TEST","faaaaaaaaaaaaaaaa::::"+ e.toString());
                    return false;
                }
            }
        }

,这是我的客户端代码。

try {
                AppFonts.serverSocket = new ServerSocket(8988);
                Log.d("TEST", "Server: Socket opened0000000000");
                AppFonts.socket = AppFonts.serverSocket.accept();
            Log.d("TEST", "Server: connection done0000000000000000");
            //    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

            String gotData = convertStreamToString(AppFonts.socket.getInputStream());
            Log.d("TEST", "Server: Socket Files,,,,,,");
            Log.d("TEST", "server: copying files0000000000 " + gotData);
            return gotData;
        } catch (IOException e) {
            Log.e("TEST", "fsat , " + e.getMessage());
            e.printStackTrace();
            return null;
        } catch (Exception e2) {
            e2.printStackTrace();
            return null;
        }

在copyfile()方法中,我已经尝试过。

-

  • 我不想关闭输出流,因为我想要两个设备之间的更多通信。
  • 当我成功地使用out.close();数据成功发送给客户端时,但不使用该数据并未到达客户端。
  • 服务器正在从copyfile()方法将数据发送给客户端。从客户端收到的数据准确地发送了我使用outputStream.close()时发送的内容;但是当我删除upputStream.close()时,什么都不会发生。或/并使用outputStream.flush();。看到Android:套接字关闭后,我尝试了flush()方法。

为了使数据连续流,您可以执行此类操作

Timer scheduler = new Timer();
scheduler.scheduleAtFixedRate(task,1000,1000);
final Runnable task = new Runnable() {
   public void run() {
       try {
           is = new ByteArrayInputStream(data.getBytes());
       } catch (Exception e) {
           log.d("TEST", e.toString());
       }
   }
};

为了连续获取更新的数据流。

关闭输出流并不意味着流中的数据将不再可用于您。这意味着您正在使用的输出流已经从内存和有序中划分,以读取您需要读取下一个数据流所需的新数据。

最新更新