Java 代码如下:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Test {
public static void main(String args[]) throws IOException {
SocketChannel c = SocketChannel.open();
c.connect(new InetSocketAddress("google.com", 80));
ByteBuffer b = ByteBuffer.allocate(1024);
b.put("Request".getBytes());
System.out.println("Write: " + c.write(b));
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
}
}
实际结果:
写入:1017 读取:0 读取:1024 读取:44
第一次,方法read()
读取 0 个字节。这并不酷。
我修改了我的代码:
b.put("Request".getBytes());
System.out.println("Write: " + c.write(b));
b.flip(); //I added this line
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
实际结果:
写入:1017 读取:1024 读取:44
它已经看起来更好了。谢谢你flip()
!
接下来,我放入缓冲区 String "Request",该 String 的长度为7,但方法write()
返回1017。
什么信息方法写入通道?
我不确定,该方法写了字符串"Request"。
好的,我再次修改了我的代码:
b.put("Request".getBytes());
b.flip(); // I added this line
System.out.println("Write: " + c.write(b));
b.flip();
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
实际结果:
写:7
和代码崩溃了......
凭什么?我的错误在哪里?
谢谢。