2012-01-26 139 views
0

是的,我確實看過關於sun的教程,他們在我的情況下沒有幫助,只傳遞了第一條命令。如何通過Java中的套接字傳輸整數或字節數組

I`ve得到了一個方法

public void openConnection() throws IOException{ 

    serverSocket = new ServerSocket(5346); 

    Socket simSocket = serverSocket.accept(); 

    is = simSocket.getInputStream(); 
    os = simSocket.getOutputStream(); 

    writer = new PrintWriter(os); 
    isReader = new InputStreamReader(is); 
    reader = new BufferedReader(isReader); 

    System.out.println("Connection succesfull."); 
} 

public void sendTo(int command) { 
    try { 
     writer.println(command); 
     writer.flush(); 
    } catch(Exception e) { 
     System.out.println("Error sending command to the robot"); 
     System.out.println(e.toString()); 
    } 
} 
在發送側

,和

public static void setUpConnection() { 
    try { 
     socket = new Socket(InetAddress.getLocalHost(), 5346); 
     is = new InputStreamReader(
       socket.getInputStream()); 
     reader = new BufferedReader(is); 
     writer = new PrintWriter(socket.getOutputStream()); 
     System.out.println("Simulator: connection succesful"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

while (true) { 
       intCommand = reader.read(); 
       ett = reader.readLine(); // does nothing, but without this line it doesn't work 
       command = (char) intCommand; 

在接收端。它可以完美地發送字符或字符的ascii數字。我需要的是改變這個代碼發送整數或簡單的字節數組而不是字符。如果我只是簡單地離開InputStream和OutputStream,它會接收到第一個命令,而這些方法不斷接收通過sendTo發送的內容。即使在套接字文檔中,它們也只能用於發送字符。

+0

看看序列化(創建一個實現可序列化的類或使用其中一個可用的serializaton API)。 – theglauber

回答

0

只需編碼您的服務器以將接收到的值存儲爲int而不是char。

+0

我該如何做到這一點,我認爲只是一個什麼樣的InputStream或smth使用的問題,因爲它發送完美的號碼,只需要接收它作爲一個字節數組,並不嘗試從它得到一個字符 – user975869

+0

如果問題在於接收方,那麼只需確保方知道來自流的內容,以便它可以將其存儲爲正確的數據類型。 – bdabmxican

相關問題