如何同时读取标准输入和套接字(java多线程套接字编程)

时间:2017-05-23 16:29:46

标签: java multithreading sockets

该程序提示用户有三个选项:

Enter an option ('m', 'f', 'x'): 

(M)essage (send)

(F)ile (request) 

e(X)it 

我只想专注于' M'和' m'选项。 (不幸的是,不允许添加"接收"选项)

运行代码的屏幕截图(服务器端错误): The 'm' should be followed by "Enter your message" but isn't

运行代码的屏幕截图(成功的客户端): This worked because the client sent a message first after typing "m"

问题是BufferedReader readStandardInput和。{ BufferedReader readFromClient无法同时执行(或至少同时读取同一行代码)。我想知道如何使它们同时执行。

代码:

try{
    OutputOptions();
    String sendingMessage = "";
    BufferedReader readFromClient = null;
    String fromClient = "";
    if(isConnected == true){
        readFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        fromClient = readFromClient.readLine();
        System.out.println("Recieved from client: " + fromClient);

      //The  4 lines above this comment are recieving a message from the client
     //the lines below this comment are reading from standard input
     //I want to be able to do both the above and the below lines at the same time (reading two types of input, standard and socket),
     //In other words, once the client sends a message after typing "m",
    //it should appear on the server side, but if i decide to type "m" first 
    //on the server side, then the client will also have to be able to
    //read that message, then afterwards be able to take in standard input

        BufferedReader readStandardInput = new BufferedReader(new InputStreamReader(System.in));
        option = readStandardInput.readLine();
        if (option.length() == 1){
              if(option.equals("m") || option.equals("M")){
                  System.out.println("Enter your message: ");
                  StandardOutput();

              }
              if(option.equals("m") || option.equals("M")){
                 System.out.println("Enter your message: ");
                 StandardOutput();

              }
              if(option.equals("f") || option.equals("F")){
                 FileTransferReceive();
              }
              if(option.equals("x") || option.equals("X")){
                 System.exit(0);
              }
              else{
                  StandardOutput();
              }
           }
           else{
                StandardOutput();
           }
        }

     //}
  }catch (IOException e){
        e.printStackTrace();
  }
  finally{ }    

Full code

Earlier version of code

我的问题是: 如何在第一个屏幕截图中使服务器能够输入选项" m"并同时从客户端套接字读取一行?

1 个答案:

答案 0 :(得分:0)

Java标准输入流和java.net.Socket正在阻止(因此,当您在readsocket.getInputStream上调用System.in时,您的应用会等到它收到某些内容),这意味着你不能在那些同一个线程中实现同时读取。

如果您设置另一个服务客户端连接的线程,您将能够在等待控制台输入时从客户端接收数据。