以下是使用非阻塞SocketChannel的方式与服务器通信,并使用Selector来处理多个通道的事件。在连接建立后,我们将SocketChannel注册到Selector上,并监听OP_CONNECT事件。
一旦连接完成,我们将SocketChannel切换到写模式并发送HTTP请求,然后将SocketChannel切换到读模式并读取服务器的响应。然后,我们可以根据需要处理响应数据。请注意,通过非阻塞方式发送HTTP请求和处理响应需要更复杂的逻辑,这只是一个简单的示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
public class NonBlockingHttpSocketDemo {
public static void main(String[] args) {
String host = "example.com"; // 请求的主机名
int port = 80; // 请求的端口号
try {
// 创建SocketChannel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
// 创建Selector并将SocketChannel注册到Selector上
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);
// 连接服务器
socketChannel.connect(new InetSocketAddress(host, port));
while (true) {
if (selector.select() > 0) {
for (SelectionKey key : selector.selectedKeys()) {
if (key.isConnectable()) {
// 完成连接
SocketChannel channel = (SocketChannel) key.channel();
if (channel.finishConnect()) {
channel.register(selector, SelectionKey.OP_WRITE);
}
}
if (key.isWritable()) {
// 发送请求
String request = "GET / HTTP/1.1\r\n"
+ "Host: " + host + "\r\n"
+ "Connection: close\r\n\r\n";
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.wrap(request.getBytes());
channel.write(buffer);
channel.register(selector, SelectionKey.OP_READ);
}
if (key.isReadable()) {
// 读取响应
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
if (bytesRead == -1) {
// 服务器关闭连接
channel.close();
selector.close();
return;
}
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(new String(bytes, "UTF-8"));
}
}
selector.selectedKeys().clear();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}