zeroCopy

作者: 八颗小牙坏脾气 | 来源:发表于2018-12-27 23:26 被阅读0次

    Server

    public class OldServer {
        public static void main(String[] args) throws Exception {
            ServerSocket serverSocket = new ServerSocket(8888);
    
            while (true) {
                Socket accept = serverSocket.accept();
                DataInputStream inputStream = new DataInputStream(accept.getInputStream());
    
                try {
                    byte[] buffer = new byte[4096];
    
                    while (true) {
                        int read = inputStream.read(buffer, 0, buffer.length);
                        if (-1 == read) {
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    Client

    public class OldClient {
        public static void main(String[] args) throws Exception {
            Socket socket = new Socket("127.0.0.1", 8888);
            String fileName = "/Users/xxx/Downloads/bigfile.txt";
    
            InputStream inputStream = new FileInputStream(fileName);
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
    
            byte[] buffer = new byte[4096];
            long readCount = 0;
            long total = 0;
    
            long startTime = System.currentTimeMillis();
    
            while ((readCount = inputStream.read(buffer)) >= 0) {
                total += readCount;
                outputStream.write(buffer);
            }
    
            System.out.println("发送总的字节数:" + total + ",耗时:" + (System.currentTimeMillis() - startTime));
    
            outputStream.close();
            inputStream.close();
            socket.close();
        }
    }
    

    Nio Server

    public class NewServer {
        public static void main(String[] args) throws Exception {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            ServerSocket serverSocket = serverSocketChannel.socket();
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(8888));
    
            ByteBuffer buffer = ByteBuffer.allocate(4096);
    
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(true);
    
                int readCount = 0;
    
                while (-1 != readCount) {
                    try {
                        readCount = socketChannel.read(buffer);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                    buffer.rewind();//very important
                }
            }
        }
    }
    

    Nio Client

    相关文章

      网友评论

          本文标题:zeroCopy

          本文链接:https://www.haomeiwen.com/subject/lijjlqtx.html