java - 使用 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());
解决方案
推荐阅读
- cassandra - 当一个节点关闭时,Cassandra 中的超时问题
- apache - Apache重写以删除文件扩展名不起作用
- python-3.x - 我安装了python3.9.5,但还是显示3.9.4版本
- bash - git bash 中的 Git 命令需要冻结凭据,并且登录弹出窗口不显示
- php - 如何允许用户在设置的限制内只更新一次数据库值
- django - 发布多张图片 Django
- r - 使图形缩小
- xml - 在 oracle 中使用 select 提取 xmltype 时出现无效字符
- azure-cosmosdb - CosmosDb 在带有数组的“array_contains”的查询中抛出异常?
- postgresql - PostgreSQL 的数据文件中可以容纳多少行?