【问题标题】:How to read and write data through Java Nio client in AndroidAndroid中如何通过Java Nio客户端读写数据
【发布时间】:2014-12-03 07:02:23
【问题描述】:

我在 java 中成功地进行客户端服务器通信,但现在我需要在 Android 而不是 java 中编写客户端。

客户端:公共类 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 中它消耗大量内存并且无法可靠运行,因为它的 while (true) 循环类似于轮询,请告诉我一些解决方案,无需轮询我就可以读写数据。

谢谢。

【问题讨论】:

    标签: android client nio


    【解决方案1】:

    在调用decode()(或get(),或write(),任何将数据从缓冲区中取出的东西)之后,您需要compact() 缓冲区。

    你不应该每次在while 循环周围分配一个新缓冲区,如果read() 返回-1,你应该打破它。我实际上根本不需要while 循环。

    【讨论】:

    • 如果我删除 while 循环,客户端将立即终止。它不会收听任何收到的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2013-02-22
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多