使用JavaNIO使用JavaSocket发送字符串的正确方法
情况是,我有一个服务器,它监听连接并使用选择器,一个客户端连接并发送一个字符串,服务器接收并发送另一个字符串到客户端,然后客户端结束 服务器正确地接收客户机发送的字符串并发送其字符串,但此时客户机进入无限循环,执行read(),但它似乎无法从缓冲区获取数据,事实上字符串始终为空,我该怎么办 服务器代码使用JavaNIO使用JavaSocket发送字符串的正确方法,java,sockets,server,client,nio,Java,Sockets,Server,Client,Nio,情况是,我有一个服务器,它监听连接并使用选择器,一个客户端连接并发送一个字符串,服务器接收并发送另一个字符串到客户端,然后客户端结束 服务器正确地接收客户机发送的字符串并发送其字符串,但此时客户机进入无限循环,执行read(),但它似乎无法从缓冲区获取数据,事实上字符串始终为空,我该怎么办 服务器代码 ByteBuffer buf = ByteBuffer.allocate(1024); buf.rewind(); StringBuilder t
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());
在
buf.put(string.getBytes())之后,您没有调用ByteBuffer#flip
代码>。你说得对,我只是忘了谢谢。更准确地说,你在写之前没有打电话。您需要在获取或写入之前翻转,然后清除或压缩@雅各布。