簡體   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