2017-03-05 187 views
0

我是新來的Java編程,我只是想獲得一個非常基本的網絡程序工作。簡單的Java網絡程序

我有2個類,一個客​​戶端和一個服務器。這個想法是客戶端簡單地向服務器發送消息,然後服務器將消息轉換爲大寫並將其發送回客戶端。

我沒有問題讓服務器向客戶端發送消息,問題是我似乎無法存儲客戶端在可變服務器端發送的消息以便轉換它,所以可以不會發回特定的消息。

這裏是我到目前爲止的代碼:

服務器端

 public class Server { 

     public static void main(String[] args) throws IOException { 
      ServerSocket server = new ServerSocket (9091); 

      while (true) { 
       System.out.println("Waiting"); 

       //establish connection 
       Socket client = server.accept(); 
       System.out.println("Connected " + client.getInetAddress()); 


      //create IO streams 
       DataInputStream inFromClient = new DataInputStream(client.getInputStream()); 
       DataOutputStream outToClient = new DataOutputStream(client.getOutputStream()); 

       System.out.println(inFromClient.readUTF()); 

       String word = inFromClient.readUTF(); 

       outToClient.writeUTF(word.toUpperCase()); 
       client.close(); 
      } 
     } 

    } 

客戶端

public class Client { 

    public static void main(String[] args) throws IOException { 

     Socket server = new Socket("localhost", 9091); 

     System.out.println("Connected to " + server.getInetAddress()); 

     //create io streams 
     DataInputStream inFromServer = new DataInputStream(server.getInputStream()); 
     DataOutputStream outToServer = new DataOutputStream(server.getOutputStream()); 

     //send to server 
     outToServer.writeUTF("Message"); 

     //read from server 
     String data = inFromServer.readUTF(); 

     System.out.println("Server said \n\n" + data); 
     server.close(); 
    } 
} 

我認爲這個問題可能是與「串字= inFromClient.readUTF(); 「線?請有人建議嗎?謝謝。

+0

你爲什麼要從服務器端的客戶端讀取兩次然後丟棄第一個UTF數據包?是的,你打印它,但你然後不轉換它? –

+1

這裏:'System.out.println(inFromClient.readUTF());'你丟棄讀入的內容。 –

回答

3

你丟棄從客戶端接收第一包:

System.out.println(inFromClient.readUTF()); // This String is discarded 

String word = inFromClient.readUTF(); 

爲什麼不會掉這些?

String word = inFromClient.readUTF(); // save the first packet received 
System.out.println(word); // and also print it 
+0

謝謝,已經修復了。我沒有意識到這個字符串被丟棄了。謝謝。 – Tom

+0

@Tom:就像從掃描儀讀入。一旦你讀入它,你就提前看到流的指針。如果你仔細考慮它是有道理的。 –

+0

這確實有道理。感謝那。 – Tom