关于IO与NIO

阻塞式

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class BioSocketThread extends Thread {
    @Override
    public void run() {
        try {
            final ServerSocket serverSocket = new ServerSocket(8080);
            for(;;){
                final Socket clientSocket = serverSocket.accept();
                System.out.println("远程地址为:" + clientSocket.getRemoteSocketAddress());
                System.out.println("接收到的请求是:" + clientSocket);
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    //获取输入流,即从服务器获取的数据
                                    final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                                    //获取输出流,即我们写出给服务器的数据
                                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(),"UTF-8"));
                                    String line = null;
                                    try {
                                        //获取 输入流的内容
                                        while (!(line = bufferedReader.readLine()).isEmpty()) {
                                            System.out.println("接收到的内容是 : " + line);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    //设置输出流
                                    //必填
                                    bufferedWriter.write("HTTP/1.1 200 OK\r\n");
//                                                    bufferedWriter.write("Host: 127.0.0.1:8080\r\n\r\n");
                                    bufferedWriter.write("Host: " + clientSocket.getRemoteSocketAddress() +"\r\n\r\n");
                                    //必填
                                    bufferedWriter.write("Content-Type: application/json;charset=UTF-8\r\n");
                                    bufferedWriter.write("Content-Encoding: gzip,deflate,compress\r\n");
//                                                    bufferedWriter.write("User-Agent:PostmanRuntime/7.1.1\r\n");


                                    bufferedWriter.write("Hello,欢迎登陆");
                                    bufferedWriter.flush();
                                    clientSocket.close();
                                }catch (IOException e){
                                    e.printStackTrace();
                                }finally {
                                    try {
                                        if(clientSocket != null){
                                            clientSocket.close();
                                        }
                                    }catch (IOException e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                ).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}

NIO

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
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.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class NioSocketThread extends Thread {
    @Override
    public void run() {
        try {
            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            serverChannel.configureBlocking(false);

            serverChannel.bind(new InetSocketAddress(8080));

            Selector selector = Selector.open();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

            //开始不断监听8080端口
            int selectNum = 0;
            for (; ; ) {
                try {
                    selectNum = selector.select(3000);
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
                if(selectNum <= 0 ){
                    System.out.println("等待新的连接......");
                    continue;
                }


                Set<SelectionKey> readyKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = readyKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        System.out.println("isAcceptable");
                        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                        SocketChannel channel = ssc.accept();
                        if(channel != null){
                            channel.configureBlocking(false);
                            channel.finishConnect();
                            channel.register(selector, SelectionKey.OP_READ);// 客户socket通道注册读操作
                        }
                    } else if (key.isReadable()) {
                        System.out.println("isReadable");
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.configureBlocking(false);
                        String receive = null;
                        try {
                            receive = receive(channel);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        BufferedReader b = new BufferedReader(new StringReader(receive));

                        String line = null;
                        //获取 输入流的内容
                        while (!(line = b.readLine()).isEmpty()) {
                            System.out.println("接收到的内容是 : " + line);
                        }

                        b.close();
                        channel.register(selector, SelectionKey.OP_WRITE);// 客户socket通道注册读操作
                    } else if (key.isWritable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        try {
                            System.out.println("isWritable");
                            StringBuilder sb = new StringBuilder();

                            sb.append("HTTP/1.1 200 OK\r\n");
                            sb.append("Host: 127.0.0.1:8080\r\n\r\n");
                            sb.append("你好,hello");
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            Charset charset = Charset.forName("GBK");
                            buffer.put(charset.encode(sb.toString()));
                            buffer.flip();
                            channel.write(buffer);

                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            channel.close();
                        }
                    }
                }
                iterator.remove();

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    // 接受数据
    private String receive(SocketChannel socketChannel) throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        byte[] bytes = null;
        int size = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((size = socketChannel.read(buffer)) > 0) {
            buffer.flip();
            bytes = new byte[size];
            buffer.get(bytes);
            baos.write(bytes);
            buffer.clear();
        }
        bytes = baos.toByteArray();

        return new String(bytes);
    }
}

Netty的阻塞式

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class NettyBioThread extends Thread {
    @Override
    public void run() {
        StringBuilder sb = new StringBuilder();

        sb.append("HTTP/1.1 200 OK\r\n");
        sb.append("Host: 127.0.0.1:8080\r\n\r\n");
        sb.append("你好,hello");

        final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(sb.toString(), Charset.forName("GBK")));
        // 第一步,创建线程池
        EventLoopGroup group = new OioEventLoopGroup();
        ServerBootstrap b = null;
        try {
            // 第二步,创建启动类
            b = new ServerBootstrap();
            // 第三步,配置各组件
            b.group(group).channel(OioServerSocketChannel.class).localAddress(new InetSocketAddress(8080)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                        }
                    });
                }
            });
            // 第四步,开启监听
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }

    }
}

Netty的非阻塞式

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class NettyNioThread extends Thread {
    @Override
    public void run() {
        StringBuilder sb = new StringBuilder();

        sb.append("HTTP/1.1 200 OK\r\n");
        sb.append("Host: 127.0.0.1:8080\r\n\r\n");
        sb.append("你好,hello");

        final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(sb.toString(), Charset.forName("GBK")));
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap b = null;
        try {
            b = new ServerBootstrap();
            b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(8080)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                        }
                    });
                }
            });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

 

posted @ 2019-05-22 22:45  me-ht  阅读(199)  评论(0编辑  收藏  举报