2013-01-22 65 views
2

我實際上想寫一個Java服務器和我的Android遊戲之間的TCP通信,以將數據保存到數據庫。曾經有一個全球鉛板。整數和字符串TCP連接

我現在實際上已經編寫了服務器,並且可以通過我寫的客戶端連接到它,並希望稍後在Android中實現。 下面是從客戶端的一些代碼:

public void saveToDatabase(String name , int level, int killpoints){ 
     try { 
      Socket soc = new Socket("localhost", PORT); 
      DataOutputStream out = new DataOutputStream(soc.getOutputStream()); 
      DataInputStream in = new DataInputStream(new BufferedInputStream(soc.getInputStream())); 

      //to call the save statement! 
      out.writeInt(0); 
      //give the stuff 

      out.writeUTF(name); 
      out.writeInt(level); 
      out.writeInt(level); 

      //close it 
      out.close(); 
      in.close(); 
      soc.close(); 

     } catch (UnknownHostException e) { 
      // TODO Auto-generated catch block 
//   e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
//   e.printStackTrace(); 
     } 
    } 

什麼服務器現在確實是得到它的第一行,並檢查這要取決於價值做什麼。在服務器出現這種情況:

public void run() { 
     try { 
      DataOutputStream out = new DataOutputStream (socket.getOutputStream()); 
//   DataInputStream in = new DataInputStream(new InputStreamReader(
//     socket.getInputStream())); 
      DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 
      Server.textArea.setText(Server.textArea.getText()+"Client connected: "+ clientNumber+ "\n"); 

      int firstLine = in.readInt(); //get first line for switch 

      switch (firstLine) { 
      case 0: 
//    getting the whole objekt for the database in own lines! 
       String name = in.readUTF(); 
       int level = in.readInt(); 
       int kp = in.readInt(); 
       Server.textArea.setText(Server.textArea.getText() + "SAVE: " 
         + name + " Level: " + level + " KP: " + kp + "\n"); 
//    Server.textArea.setText(Server.textArea.getText() + "SAVE called\n");  
       break; 
      case 1: 
       // else if return the top10 
       Server.textArea.setText(Server.textArea.getText() 
         + "Return top10\n"); 
       // outp.write("asdf string"); 
       break; 
      default: 
       break; 
      } 

      out.close(); 
      in.close(); 
      socket.close(); 
      Server.textArea.setText(Server.textArea.getText() 
        + "Client disconnected: "+ clientNumber + "\n"); 
     } catch (Exception e) { 
      System.out.println("IO error " + e); 
     } 
    } 

我登錄服務器端的一切,一個textarea和實際上可以得到這個在服務器端: consolebug

我犯com.saveToDatabase("test", 2, 123651); 如果我給的一切,UTF我居然得到也有一些strage東西:enter image description here

希望你能幫助我,甚至可以告訴我,如果這也適用於android。非常感謝。 目前它不傳輸正確的字符串。

SAVE: Level: 1908 KP: 1702065249 
Client disconnected: 0 

回答

2

您的代碼有太多問題。 您編寫了一個int(writeInt),但您在服務器上讀取了一個字節(讀取)。 另外writeUTF在線上只放一個字符串,但是你用一個新行讀取一個字符串。 使用DataInputStream讀取相應的DataOutputStream。 還要在套接字之前關閉輸出流。

+0

實際上這是誤會。我沒有看到我使用differend輸入和輸出流。改變了我的代碼。但是現在仍然對String產生了誤會。這是一個空字符串,現在。 – BennX

+0

解決並修正了代碼。謝謝。 – BennX