Java socket非阻塞发送http请求

本文介绍了一个使用Java的非阻塞SocketChannel和Selector技术,实现在Java中与服务器进行HTTP通信的示例,包括连接、发送请求、接收响应等过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是使用非阻塞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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值