2014-12-03 37 views
0

我在java中成功完成客戶端服務器通信,但現在我需要在Android中編寫客戶端,而不是Java。如何通過Android中的Java Nio客戶端讀取和寫入數據

客戶端:公共類ExampleClient2 {

public static void main(String[] args) throws IOException, 
InterruptedException { 
    int port = 1114; 
    SocketChannel channel = SocketChannel.open(); 


    // we open this channel in non blocking mode 
    channel.configureBlocking(false); 
    channel.connect(new InetSocketAddress("192.168.1.88", port)); 

    if(!channel.isConnected()) 
    { 
     while (!channel.finishConnect()) { 
      System.out.println("still connecting"); 
     } 
    } 
    System.out.println("connected..."); 


    while (true) { 
     // see if any message has been received 
     ByteBuffer bufferA = ByteBuffer.allocate(60); 
     int count = 0; 
     String message = ""; 
     while ((count = channel.read(bufferA)) > 0) { 
      // flip the buffer to start reading 
      bufferA.flip(); 
      message += Charset.defaultCharset().decode(bufferA); 

     } 

     if (message.length() > 0) { 
      System.out.println("message " + message); 
      if(message.contains("stop")) 
      { 
       System.out.println("Has stop messages"); 
       //     break; 
      } 
      else 
      { 
       // write some data into the channel 
       CharBuffer buffer = CharBuffer.wrap("Hello Server stop from client2 from 88"); 
       while (buffer.hasRemaining()) { 
        channel.write(Charset.defaultCharset().encode(buffer)); 
       } 
      } 
      message = ""; 
     } 

    } 
} 

}

這段代碼是在java中成功運行,但在Android中它消耗大量內存和不可靠的運行,由於其同時(true)循環它像投票,PLZ讓我知道一些解決方案,沒有輪詢我可以讀取和寫入數據。

謝謝。

回答

0

您需要compact()調用decode()(或get()write(),任何將數據帶出緩衝區)的緩衝區。

Youu不應該每次都在while循環周圍分配一個新的緩衝區,如果read()返回-1,則應該跳出該緩衝區。根本沒有看到while循環的需要。

+0

如果我刪除while循環,客戶端將立即終止。它不會收聽任何收到的消息。 – Rahul 2014-12-08 13:55:55

+0

那麼你需要保留閱讀,但不是在整個循環。 – EJP 2016-01-21 00:43:49

相關問題