如何使用套接字通道连接到远程网络服务器



我正在尝试通过Java NIO socketChannel获取Web服务器发送的响应。套接字通道的读取调用在非阻塞时不返回任何内容

clientSocket.configureBlocking(false);

当指定true时,表示阻塞模式,则返回响应。有人说我们应该在启用非阻塞模式时使用Selector。但是我没有找到实现它的方法。

仅供参考,以下是我正在尝试的代码片段。

public static void main(String[] args) throws IOException, InterruptedException
{
URL u = new URL("http://www.google.com");
InetSocketAddress addr = new InetSocketAddress("www.google.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET " + u.getFile() + " HTTP/1.0rn").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);      
ByteBuffer  readBuff = MappedByteBuffer.allocate(1500);
clientSocket.read(readBuff);
while(clientSocket.read(readBuff) > 0)
{
System.out.println(new String(readBuff.array()).trim());
}
clientSocket.close();
}

提前谢谢。

您应该使用循环来read()write(),直到缓冲区在非阻塞模式下没有剩余字节。

代码中有两个问题:

  1. HTTP 请求正文错误。它需要额外的"\r"。
  2. 阅读后每次都需要清除读取Buff。

下面的代码是一个工作版本:

static void working() throws Exception {
URL u = new URL("http://www.baidu.com");
InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET / HTTP/1.0rnrn").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
while (clientSocket.read(readBuff) != -1) {
System.out.println("Entring...");
System.out.println(new String(readBuff.array()).trim());
readBuff.clear();
}
clientSocket.close();
}

}

注意,如果是http版本1.1,它也不会中断。 因为它有一个Keeplive。

相关内容

最新更新