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让我知道一些解决方案,没有轮询我可以读取和写入数据。
谢谢。
如果我删除while循环,客户端将立即终止。它不会收听任何收到的消息。 – Rahul 2014-12-08 13:55:55
那么你需要保留阅读,但不是在整个循环。 – EJP 2016-01-21 00:43:49