我想同时从服务器读取和写入,但不能同时读取和写入

时间:2018-10-01 19:27:41

标签: java sockets

我有一个服务器类,该类具有一个主要方法,该方法使用while(true)保持服务器运行。我有在while循环中读取和写入数据的代码。我有一个具有3种方法的客户端类,第一种方法读取数据,第二种方法和第三种方法写入数据。我还有另一个称为显示控制器的类,它根据我们在应用程序中的工作来调用客户端类中的方法。

public class Server {
public static void main(String[] args) throws IOException {
  ServerSocket serverSocket = new ServerSocket(666);
    FileReader fileReader = new FileReader("MYJSON.json");
    BufferedReader buff = new BufferedReader(fileReader);
    while (true) {
      Socket socket = serverSocket.accept();

  /*   InputStreamReader inputStreamReader = new 
      InputStreamReader(socket.getInputStream());
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str = bufferedReader.readLine();
      writeJson(str); */

      String str;
      OutputStreamWriter outputStreamWriter = new
      OutputStreamWriter(socket.getOutputStream());
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      str = buff.readLine();
      printWriter.write(str);
      printWriter.flush();
      printWriter.close();

      InputStreamReader inputStreamReader = new 
      InputStreamReader(socket.getInputStream());
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str1 = bufferedReader.readLine();
      if (str1.equals("createNewJson")) {
        fileReader = new FileReader("MYJSON.json");
      }

    }
  }

import java.io.*;

    import java.net.Socket;

    public class Client{

    public static String readDataFromServer() throws IOException{
    Socket socket = new Socket("localhost",666);
    InputStreamReader inputStreamReader = new 
    InputStreamReader(socket.getInputStream());
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    System.out.println();
    String str = bufferedReader.readLine();
    System.out.println(str);
    return str;

    }

    public static void createNewJsonFile() throws IOException {
      Socket socket = new Socket("localhost",666);
      OutputStreamWriter outputStreamWriter = new 
      OutputStreamWriter(socket.getOutputStream());
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.write("CreateNewJson");
    }

      public static void writeDataToServer(String str) throws IOException {
       Socket socket = new Socket("localhost",666);

        OutputStreamWriter outputStreamWriter = new 
        OutputStreamWriter(socket.getOutputStream());
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.write(str);
        printWriter.flush();
        printWriter.close();

        }


    }

问题是,当在客户端类中调用read方法时,服务器正在执行while循环中的代码以将数据发送到服务器,但是它还执行用于从客户端(但客户端)读取数据的代码未发送任何数据,因为未调用客户端类中的write方法。我不要因此,当它执行代码读取数据时,出现连接重置错误。我知道这是因为我的服务器不必要地在while循环中执行了读取数据的代码行,即使客户端没有向服务器发送任何数据来进行读取。无论如何,我可以解决这个问题吗?

0 个答案:

没有答案