Дополнительные символы записываются в файл с клиента на сервер - PullRequest
0 голосов
/ 04 октября 2018

Я отправляю текст между клиентом и сервером с Java.Это делается путем отправки потока байтов от клиента к серверу.Строка, которая была преобразована из потока байтов, затем сохраняется в папке с метками времени, в результате чего она записывается в файл.К сожалению, пробел, а также неожиданные символы, такие как «^ @», записываются в файл вместе с ожидаемым текстом.

В чем может быть проблема?Я думаю, что это может быть ошибка преобразования буфера в строку, но я могу ошибаться.

Я приложил вывод времени выполнения из терминала, а также весь полезный код, в котором, по моему мнению, возникает проблема.Объяснение этой проблемы, а не просто ответ, было бы наиболее полезным, поскольку я хотел бы узнать, почему возникает такая ошибка.

Основной метод:

public static void main(String[] args) {
  startServer();


  String date = createDateString(); 
  String miniDate = createMiniDateString(); 

  System.out.println("hello, we are still waiting to start...");


  try {
    Socket       connection;
    OutputStream tx;
    InputStream  rx;

    connection = server_.accept(); // waits for connection
    tx = connection.getOutputStream();
    rx = connection.getInputStream();
    server_.close(); // no need to wait now

    System.out.println("We are here now");

    System.out.println("New connection ... " +
        connection.getInetAddress().getHostName() + ":" +
        connection.getPort());

    byte[] buffer = new byte[bufferSize_];
    int b = 0;
    while (b < 1) {
      Thread.sleep(sleepTime_);

      buffer = new byte[bufferSize_];
      b = rx.read(buffer);
    }

    if (b > 0) {

      //I believe the problem might be due to buffer to string conversion
      String s = new String(buffer); //this is the message, we might have to store it in an array instead?
      System.out.println("Received " + b + " bytes --> " + s);

      System.out.println("***** this is the string: *****"+s);

      System.out.println("Sending " + b + " bytes");
      tx.write(buffer, 0, b); // send data back to client

      createDirectory(s, date, miniDate);

      connection.close(); // finished
    }


  }

  catch (SocketTimeoutException e) {
    // no incoming data - just ignore
  }
  catch (InterruptedException e) {
    System.err.println("Interrupted Exception: " + e.getMessage());
  }
  catch (IOException e) {
    System.err.println("IO Exception: " + e.getMessage());
  }
}

Метод createDirectory:

public static void createDirectory(String s, String date, String miniDate){


  String dirName = new String(date);//time1
  String fileName = new String(miniDate); //time2
  String text = new String(s); //message

  File dir = new File(dirName); //copy these raw at first and then clean it up as a new method

  if (dir.exists()) {
    System.out.println("++ File already exists: " + dirName);
    //System.exit(0);
  }

  if (dir.mkdir()) {
    System.out.println("++ Created directory: " + dirName);
  }
  else {
    System.out.println("++ Failed to create directory: " + dirName);
    //System.exit(0);
  }

  fileName = dirName + File.separator + fileName;
  File file = new File(fileName);

  if (file.exists()) {
    System.out.println("++ File already exists: " + fileName);
    //System.exit(0);
  }

  try {
    FileWriter fw = new FileWriter(file);
    fw.write(text);
    fw.flush();
    fw.close();
  }
  catch (IOException e) {
    System.out.println("IOException - write(): " + e.getMessage());
  }

  System.out.println("++ Wrote \"" + text + "\" to file: " + fileName);

}

Вывод в файл

Связь на стороне клиента

Вывод терминала на стороне сервера

1 Ответ

0 голосов
/ 04 октября 2018

Вы пытаетесь преобразовать в строку весь буфер (все bufferSize_ байты), но только первые b байты буфера содержат данные, полученные от клиента.Используйте

String s = new String(buffer, 0, b);

для преобразования только первых b байтов массива байтов (см. ответ )

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...