Java BIO NIO AIO,Integer和String必问知识点

public class NIOServerHandle implements Runnable{

private int port;

private ServerSocketChannel serverSocketChannel;

private Selector selector;

private volatile boolean start;



public NIOServerHandle(int port) {

    this.port = port;

    try {

        selector = Selector.open();

        serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        start = true;

        System.out.println("NIOServer启动服务,端口:" + port);



    }catch (Exception e) {

        System.out.println("封装NIO服务失败");

        System.out.println(e);

    }

}

@Override

public void run(){

    while(start) {

        try{

            //没1秒唤醒一次,轮询一遍事件

            selector.select(1000);

            Set selectionKeys = selector.selectedKeys();

            Iterator it = selectionKeys.iterator();

            SelectionKey selectionKey = null;

            while(it.hasNext()) {

                selectionKey = it.next();

                it.remove();

                try{

                    handleInput(selectionKey);

                }catch(Exception e){

                    System.out.println("服务获取信息失败");

                    System.out.println(e);

                }

            }

        }

        catch (Exception e) {

            System.out.println(e);

        }

    }

    if(selector != null)

        try{

            selector.close();

        }catch (Exception e) {

            e.printStackTrace();

        }



}



public void stop() { start = false;}



private void handleInput(SelectionKey key) throws Exception{

    if(key.isValid()) {

        if(key.isAcceptable()) {

            ServerSocketChannel channel = (ServerSocketChannel) key.channel();

            SocketChannel socketChannel = channel.accept();

            socketChannel.configureBlocking(false);

            socketChannel.register(selector, SelectionKey.OP_READ);



        }

        if(key.isReadable()) {

            SocketChannel socketChannel = (SocketChannel)key.channel();

            //分配1M的buffer

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            int size = socketChannel.read(byteBuffer);

            if(size > 0) {

                //将缓冲区当前的limit设置为position=0,用于后续对缓冲区的读取操作

                byteBuffer.flip();

                byte[] bytes =  new byte[byteBuffer.remaining()];

                //复制到bytes中

                byteBuffer.get(bytes);

                String contents = new String(bytes, "UTF-8");

                System.out.println("NIO服务收到消息:"+contents);



                String expression = new String(bytes,"UTF-8");

                System.out.println("服务器收到消息:" + expression);

                doWrite(socketChannel, "收到信息,你好,我是NIO");

            }

            else if(size < 0) {

                key.cancel();

                socketChannel.close();

            }

        }

    }

}



private void doWrite(SocketChannel channel, String msg) {

    try {

        byte[] bytes = msg.getBytes();

        ByteBuffer writebuffer = ByteBuffer.allocate(bytes.length);

        writebuffer.put(bytes);

        //postion,limit值的交换,用于输出buffer

        writebuffer.flip();

        channel.write(writebuffer);

    }catch (Exception e) {

        System.out.print("[error]: NIOserver发送信息失败");

        e.printStackTrace();

    }

}

}




### []( )NIO 客户端代码



_提示_



1.  类Client用于启动NIO客户端,传输参数只有IP、PORT

2.  类ClientHandle用于NIO客户端请求服务端以及处理服务端的数返回数据



#### []( )NIO客户端启动类



package com.ruider.customerNIO;

/**

  • Created by mahede on 2018/11/21.

*/

public class Client {

private static final String IP_ADDRESS = "localhost";

private static final int PORT = 1234;

private static ClientHandle clientHandle;



public static void start(){ start(IP_ADDRESS, PORT);}



private synchronized static void start(String host, int port) {

    if(clientHandle != null) {

        clientHandle.stop();

    }

    clientHandle = new ClientHandle(IP_ADDRESS, PORT);

    new Thread(clientHandle, "Client").start();

}



//向服务器发送消息

public static boolean sendMsg(String msg) throws Exception{

    if(msg.equals("q")) return false;

    clientHandle.sendMsg(msg);

    return true;

}

}




#### []( )客户端发送请求和处理返回数据类



package com.ruider.customerNIO;

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.util.Iterator;

import java.util.Set;

/**

  • Created by mahede on 2018/11/21.

*/

public class ClientHandle implements Runnable {

private String ipAddress;

private int port;

private SocketChannel socketChannel;

private Selector selector;

private static boolean start;



public ClientHandle(String host, int port) {

    try{

        this.ipAddress = host;

        this.port = port;

        selector = Selector.open();

        socketChannel = SocketChannel.open();

        socketChannel.configureBlocking(false);

        //socketChannel.connect(new InetSocketAddress(ipAddress, port));

        //socketChannel.register(selector, SelectionKey.OP_CONNECT);

        start = true;

        System.out.println("客户端启动");

    }catch (Exception e) {

        System.out.println("客户端启动失败");

        e.printStackTrace();

    }



}



public static void stop() { start = false;}



public void sendMsg(String msg) throws Exception{

    socketChannel.register(selector, SelectionKey.OP_READ);

    doWrite(socketChannel, msg);

}



@Override

public void run() {

    try{

        doConnect();

    }catch (Exception e){

        e.printStackTrace();

        System.exit(1);

    }



    while (start) {

        try {

            selector.select(1000);

            Set selectionKeys = selector.selectedKeys();

            Iterator it = selectionKeys.iterator();

            SelectionKey key = null;

            while (it.hasNext()) {

                key = it.next();

                it.remove();

                try {

                    handleInput(key);

                }

                catch (Exception e) {

                    if(key != null){

                        key.cancel();

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。

CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

                if(key != null){

                        key.cancel();

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。

CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

蚂蚁金服5面,总结了49个面试题,遇到的面试官都是P7级别以上

你可能感兴趣的:(程序员,java,udp,后端)