2014-12-03 83 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

相关问题