【发布时间】:2011-07-08 11:20:09
【问题描述】:
我试图使用 java NIO 实现一个简单的 HTTP 客户端。但是我收到一个错误,即在读取所有数据之前,远程主机强制关闭了连接。 使用普通套接字,一切正常。
这是一个例子:
private static final String REQUEST = "GET / HTTP/1.1\r\nHost: stackoverflow.com\r\n\r\n";
void channel() {
try {
SocketChannel sc = SocketChannel.open(new InetSocketAddress("stackoverflow.com", 80));
while (!sc.isConnected()) {
}
ByteBuffer buf = ByteBuffer.allocate(16*1024);
buf.put(REQUEST.getBytes());
buf.rewind();
sc.write(buf);
buf.rewind();
while (sc.read(buf) > 0) {
buf.rewind();
System.out.println(new String(buf.array()));
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
void socket() {
try {
Socket s = new Socket("stackoverflow.com", 80);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.write(REQUEST);
out.flush();
String l;
while ((l = in.readLine()) != null) {
System.out.println(l);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// Works:
new Test().socket();
// Exception:
new Test().channel();
}
这是我得到的例外:
java.io.IOException: An existing connection was forcibly closed by the remote host
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(Unknown Source)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.read(Unknown Source)
at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
at at.maph.tlsproxy.client.Test.channel(Test.java:39)
at at.maph.tlsproxy.client.Test.main(Test.java:70)
是否与我在套接字上使用缓冲阅读器而不是在通道上使用有关?如果是这样,我怎样才能让一个通道缓冲读取的数据?
【问题讨论】:
-
您忽略了 write() 的结果。它返回了什么?您的“while (!sc.isConnected())”循环也毫无意义。它永远无法使用这种阻塞模式代码执行:套接字要么在 open() 调用后连接,要么抛出异常。
-
好的,我在检查write()的返回值后发现了,它是16.384,所以随机数据被发送到服务器。问题在于在缓冲区上调用
rewind,而必须使用flip!
标签: java sockets exception nio