博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于IO与NIO
阅读量:4573 次
发布时间:2019-06-08

本文共 11900 字,大约阅读时间需要 39 分钟。

阻塞式

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
readyKeys = selector.selectedKeys(); Iterator
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
() { @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
() { @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 { } } }}

 

转载于:https://www.cnblogs.com/huangtao1927/p/IO.html

你可能感兴趣的文章
Celery框架
查看>>
[c#]asp.net开发微信公众平台(4)关注事件、用户记录、回复文本消息
查看>>
[转载,感觉写的非常详细]DUBBO配置方式详解
查看>>
Android在Eclipse上的环境配置
查看>>
面向对象(五)
查看>>
android平台下使用点九PNG技术
查看>>
Python学习3,列表
查看>>
最长回文子串
查看>>
JAVA基础-JDBC(一)
查看>>
js中for和while运行速度比较
查看>>
算法第5章作业
查看>>
7.9 练习
查看>>
基于ArcGIS JS API的在线专题地图实现
查看>>
learnByWork
查看>>
lua 函数
查看>>
Git的基本命令
查看>>
四平方和
查看>>
第十八周 12.27-1.2
查看>>
C# IP地址字符串和数值转换
查看>>
TCHAR和CHAR类型的互转
查看>>