首页 > 解决方案 > 使用 java NIO 使用 java 套接字发送字符串的正确方法

问题描述

情况是这样我有一个服务器,它监听连接并使用选择器,客户端连接并发送一个字符串,服务器接收它并向客户端发送另一个字符串,之后客户端结束。

服务器正确接收到客户端发送的字符串并发送它的字符串但是此时客户端进入了一个无限循环,执行了 read() 但它好像无法从缓冲区中获取数据,实际上字符串是总是空荡荡的,我该怎么办?

服务器代码

ByteBuffer buf = ByteBuffer.allocate(1024);                         
buf.rewind();
StringBuilder tmp = new StringBuilder();
while(client.read(buf)>0) {                         
    buf.flip();
    while(buf.hasRemaining()) {
        tmp.append((char) buf.get());
    }
    buf.clear();
}
System.out.println("String received " + tmp.getBytes());                    
String string = "hello"

buf.rewind();
buf.put(string.getBytes());
while(buf.hasRemaining()) {
    client.write(buf);
}
buf.clear();
System.out.println("Sending complete.");

客户端代码

ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(message.getBytes());            
buf.flip();
while(buf.hasRemaining()) {
    socket.write(buf);
}
buf.clear();
StringBuilder string = new StringBuilder();
buf.rewind();
while(socket.read(buf)>0){
    //the client read something cause execute these commands
    buf.flip();
    while(buf.hasRemaining()) {
        //then enter in this infinite loop
        string.append((char) buf.get());
        //It only prints "Read: " no sing of the rest of the string
        System.out.println("Read: " +string.toString());
    }
    buf.clear();                    
}
System.out.println("Client has received: " + string.toString());

标签: javasocketsserverclientnio

解决方案


推荐阅读