Java NIO:连接被强制关闭
我试图使用JavaNIO实现一个简单的HTTP客户机。但是我得到一个错误,在读取所有数据之前,远程主机强制关闭了连接。 使用普通插座,一切正常 下面是一个例子:Java NIO:连接被强制关闭,java,sockets,exception,nio,Java,Sockets,Exception,Nio,我试图使用JavaNIO实现一个简单的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
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()
的返回值(16.384)后找到了它,所以随机数据被发送到服务器。问题在于调用缓冲区时,必须使用:
void channel() {
try {
SocketChannel sc = SocketChannel.open(new InetSocketAddress("stackoverflow.com", 80));
ByteBuffer buf = ByteBuffer.allocate(16*1024);
buf.put(REQUEST.getBytes());
buf.flip(); // <--------- Here
sc.write(buf);
buf.rewind();
while (sc.read(buf) > 0) {
buf.flip(); // <------- And here
System.out.println(new String(buf.array()));
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
void channel(){
试一试{
SocketChannel sc=SocketChannel.open(新的InetSocketAddress(“stackoverflow.com”,80));
ByteBuffer buf=ByteBuffer.allocate(16*1024);
buf.put(REQUEST.getBytes());
buf.flip();//0){
buf.flip();//您正在忽略write()的结果。它返回了什么?而且您的“while(!sc.isConnected())”循环是毫无意义的。它永远无法使用此阻塞模式代码执行:套接字在open()调用后连接,或者抛出了异常。好的,我在检查write()后现在就解决了这个问题的返回值为16.384,因此随机数据被发送到服务器。问题是在缓冲区上调用revind
,而必须使用flip
!