繁体   English   中英

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

[英]How to read from standard input and from a socket at the same time (java multithreaded socket programming)

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

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

(M)essage (send)

(F)ile (request) 

e(X)it 

我只想关注“ M”和“ m”选项。 (不幸的是,不允许添加“接收”选项)

正在运行的代码的屏幕截图(服务器端错误): “ m”后应跟“输入您的信息”,但不要


运行代码的屏幕快照(成功的客户端): 之所以有效,是因为客户端在键入“ m”后首先发送了一条消息


问题是BufferedReader readStandardInputBufferedReader 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{ }    

完整代码

早期版本的代码

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

Java标准输入流和java.net.Socket被阻挡(所以一旦你叫read在任的socket.getInputStreamSystem.in您的应用程序会等到它收到的东西),这意味着你不能同时实现在同一个线程读取从那些。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM