2011-03-09 82 views
0

我試圖從Java客戶端向C++服務器發送協議緩衝區消息。運行服務器和客戶端後,我只是將「0」作爲Api字段的值,即使我在Java客戶端將其設置爲「1」。從Java客戶端向C++服務器發送協議緩衝區消息

Java客戶端代碼如下所示:

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

    Socket echoSocket = null; 
    PrintWriter out = null; 
    BufferedReader in = null; 

    //the protocol buffers message is called INFO and have only one field Api 

    INFO info = INFO.newBuilder()  

      .setApi(1)     

      .build(); 

    try { 
    echoSocket = new Socket("localhost", 30000); 
    out = new PrintWriter(echoSocket.getOutputStream(), true); 
    in = new BufferedReader(new InputStreamReader(
            echoSocket.getInputStream())); 
    } catch (UnknownHostException e) { 
     System.err.println("Don't know about host: Localhost."); 
     System.exit(1); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for " 
          + "the connection to: Localhost."); 
     System.exit(1); 
    } 


    out.println((info.toByteArray())); // serialize and the message 
    System.out.println("send "); 
    } 
    } 

而C++服務器的代碼如下所示:

int main (int argc, int argv[]){ 


INFO info; 

try 
{ 
    // Create the socket 
    ServerSocket server (30000); 


    while (true) 
      { 


    ServerSocket new_sock; 
    server.accept (new_sock); 

    try 
    { 


     while(true){ 

     std::string data; 

    // in the next i'll i receive Data from the Java client i already test it with a string, and it works 

     new_sock >> data;     

     info.ParseFromString(data); 

     cout << "api: " << info.api() << endl;    

     } 
    } 

    catch (SocketException&) {} 
      } 

    } 
     catch (SocketException& e) 
     { 
    std::cout << "Exception was caught:" << e.description() << "\nExiting.\n"; 
} 

    return 0; 
    } 

我不知道我做錯了。我不知道我是否正確序列化解析。我沒有得到任何錯誤只有一個虛假的Api值。請讓我知道如果你看到任何問題!非常感謝!

+1

您應該添加調試消息,以檢查您是否確實收到的字節數與發送的字節數相同。我不認爲這個「new_sock」數據;「與換行符和'\ 0'字符正常工作。 ProtoBuf消息不包含有關自身長度的信息。當你通過原始套接字發送它們時,你必須首先告訴對方以下消息的長度。您應該看看CodedInputStream和CodedOutputStream的原型。 – 2011-03-23 11:35:15

回答

0

我認爲這個問題是:

​​

驗證爲data讀取的字節數是一樣的info.toByteArray()大小。我的猜測是他們不一樣,在這種情況下,你需要改變你從new_sock(默認情況下換行符分隔IO)的數據的方式。

相關問題