java 纯nio使用 serverSocketChannel与socketChannel 最简单的例子,没有使用select,多线程等等

本文通过两个Java程序实例,展示了如何使用NIO进行网络编程。第一个程序为服务器端,监听指定端口并处理客户端请求;第二个程序为客户端,向服务器发起HTTP请求并接收响应。文章详细介绍了非阻塞I/O模型下,如何利用Selector机制高效地处理多个连接。

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

serverSocketChannel 是服务器端,监听端口,等待链接
Test2.java 是先监听端口,设置非阻塞,轮训seletor上的channel,根据channel的不同状态读取

运行main后,查看http头与body
curl -i 127.0.0.1:8080

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author zhanghui
 * @date 2019/6/28
 */
public class Test2 {

    public static void main(String[] args) {

        Selector selector = null;
        int port = 8080;
        try {
            selector = SelectorProvider.provider().openSelector();

            ServerSocketChannel serverChannel = SelectorProvider.provider().openServerSocketChannel();
            serverChannel.configureBlocking(false);
            serverChannel.bind(new InetSocketAddress("127.0.0.1", port));
            System.out.printf("Listen on port:"+port);
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

            Test2.loopSelect(selector);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void loopSelect(Selector selector){

        while (true){
            //对socket异常处理,关闭
            SelectionKey selectionKey = null;
            try {
                int ready = selector.select();
                if (ready <= 0) continue;

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();

                while(it.hasNext()){
                    selectionKey = it.next();

                    //不同类型处理,一个key可能是多个类型合集
                    if(selectionKey.isAcceptable()){
                        ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.finishConnect();

                        Request request = new Request();
                        request.setSocketChannel(socketChannel);
                        request.setRequestId(UUID.randomUUID().toString());

                        SelectionKey key = socketChannel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE); //http连接后,读写会同时就绪,保证先读
                        key.attach(request);

                    }
                    //ServerSocketChannel直接来读写了
                    if (!(selectionKey.channel() instanceof SocketChannel)){
                        it.remove();
                        continue;
                    }
                    if(selectionKey.isReadable()){
                        Request request = (Request) selectionKey.attachment();
                        SocketChannel socketChannel = request.getSocketChannel();
                        //循环读取,确定读取结束
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        int len = 0;
                        boolean readDone = false;
                        while (!readDone){
                            while((len = socketChannel.read(buf))>0){
                                buf.flip();
                                String tmp = new String(buf.array(),0,len);
                                System.out.println(tmp);
                                buf.clear();

                                //判断结束,get请求,末尾是两个换行
                                if(tmp.contains("\r\n\r\n")){
                                    readDone = true;
                                    break;
                                }
                            }
                        }

                        request.setReaded(true);
                        selectionKey.attach(request);
                    }
                    if(selectionKey.isWritable()){
                        Request request = (Request) selectionKey.attachment();
                        SocketChannel socketChannel = request.getSocketChannel();

                        //如果这个socketChannel还没有被先读
                        if(!request.isReaded()){
                            it.remove();
                            continue;
                        }

                        String sendStr = "Http/1.1 200 Ok\r\n" +
                                "Content-Type:text/html;charset=UTF-8\r\n" +
                                "\r\n" +
                                "<html><head><title>demo page</title></head><body>hi,world</body></html>";
                        ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes(StandardCharsets.UTF_8));
                        socketChannel.write(buf);

                        System.out.println("socket id:"+ request.getRequestId()+" done");
                        socketChannel.close();
                    }

                    it.remove();
                }

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    selectionKey.channel().close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

//请求包装类
class Request{
    private SocketChannel socketChannel = null;
    private String requestId;
    private boolean readed = false;

    public SocketChannel getSocketChannel() {
        if(socketChannel == null)
            throw new RuntimeException("no socketChannel");
        return socketChannel;
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public boolean isReaded() {
        return readed;
    }

    public void setReaded(boolean readed) {
        this.readed = readed;
    }
}

socketChannel是连接服务使用,可以访问web服务器或做proxy代理服务

启动main后,控制台打印得到的http信息,现在很多都启用了全站https,所以很多都是返回302
和Test2.java过程类似,设置与开启selector轮训,然后根据channel的状态

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author zhanghui
 * @date 2019/6/26
 */
public class Test {


    public static void main(String[] args) {

        try {
            Selector selector = SelectorProvider.provider().openSelector();
//            String url = "ifeve.com";
//            int port = 80;
            String url = "127.0.0.1";
            int port = 8080;

            SocketChannel socketChannel = SelectorProvider.provider().openSocketChannel();
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(url, port));
            socketChannel.register(selector,SelectionKey.OP_CONNECT);

            Test.loopSelect(selector);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void loopSelect(Selector selector){
        boolean isFinish = false;
        while (!isFinish) {
            try {
                int ready = selector.select();
                if (ready <= 0) continue;

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();

                    if(selectionKey.isConnectable()){
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        if(socketChannel.finishConnect())
                        {
                            RequestTo requestTo = new RequestTo();
                            requestTo.setRequestId(UUID.randomUUID().toString());
                            requestTo.setSocketChannel(socketChannel);

                            SelectionKey selectionKey1 = socketChannel.register(selector,SelectionKey.OP_WRITE | SelectionKey.OP_READ);
                            selectionKey1.attach(requestTo);
                        }else{
                            throw new RuntimeException("connection failed");
                        }
                    }
                    if(selectionKey.isReadable()){
                        RequestTo requestTo = (RequestTo) selectionKey.attachment();
                        SocketChannel socketChannel = requestTo.getSocketChannel();

                        //未发送过请求
                        if(!requestTo.isWrited()){
                            it.remove();
                            continue;
                        }

                        int len = 0;
                        ByteBuffer buf = ByteBuffer.allocate(10240);
                        while ((len = socketChannel.read(buf)) != -1) {
                            buf.flip();
                            String tmp = new String(buf.array(),0,len);
                            System.out.println(tmp);
                            buf.clear();

                            //判断读取完毕, content-length, chunked, 等等,确定长度,比较复杂
                            break;
                        }
                        socketChannel.close();
                        return;
                    }
                    if(selectionKey.isWritable()){
                        RequestTo requestTo = (RequestTo) selectionKey.attachment();
                        SocketChannel socketChannel = requestTo.getSocketChannel();

                        String url = "ifeve.com";

                        String sendStr = "GET / HTTP/1.1\r\n" +
                                "Host: " + url + "\r\n" +
                                "\r\n";
                        ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes(StandardCharsets.UTF_8));


                        socketChannel.write(buf);

                        requestTo.setWrited(true);
                    }

                    it.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
                isFinish = true;
            }
        }
    }
}

class RequestTo{
    private SocketChannel socketChannel = null;
    private String requestId;
    private boolean writed = false;

    public SocketChannel getSocketChannel() {
        if(socketChannel == null)
            throw new RuntimeException("no socketChannel");
        return socketChannel;
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public boolean isWrited() {
        return writed;
    }

    public void setWrited(boolean writed) {
        this.writed = writed;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值