美文网首页
nio实现socket

nio实现socket

作者: 0012 | 来源:发表于2022-04-14 17:54 被阅读0次

    1、nio实现socket

    服务段

    
    package socketnio;
    
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.*;
    import java.util.Iterator;
    import java.util.Set;
    
    public class NioSocketServer {
    
        static Selector selector = null;
        static ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        public static void main(String[] args) throws Exception{
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    
            //必须设置成非阻塞的
            serverSocketChannel.configureBlocking(false);
    
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",9999));
    
    
            selector = Selector.open();
    
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    
            while (true){
                if(selector.select(3000) == 0){
                    System.out.println("未获取到客户端链接当前线程非阻塞运行");
                    continue;
                }
    
    
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
    
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
    
                while (iterator.hasNext()){
    
                    SelectionKey next = iterator.next();
    
                    //客户端发起连接
                    if(next.isAcceptable()){
                        acceptAdapter(next);
                    }else if (next.isReadable()){
                        readAdapter(next);
                    }else if (next.isWritable()){
                        witerAdapter(next);
                    }
                    iterator.remove();
                }
            }
        }
    
        public static void acceptAdapter(SelectionKey selectionKey) throws Exception{
    
            ServerSocketChannel channel = (ServerSocketChannel)selectionKey.channel();
    
            SocketChannel accept = channel.accept();
    
            accept.configureBlocking(false);
    
    
            accept.register(selector,SelectionKey.OP_READ);
            System.out.println("当前客户端已经绑定到选择器READ事件中" + accept.getRemoteAddress().toString());
    
        }
    
        public static void readAdapter(SelectionKey selectionKey) throws Exception{
            SocketChannel channel = (SocketChannel)selectionKey.channel();
    
            byteBuffer.clear();
            int a;
    
            int read = channel.read(byteBuffer);
            byteBuffer.flip();
            System.out.println("客户端传递的内容为:" + new String(byteBuffer.array(),0,read));
            channel.register(selector,SelectionKey.OP_WRITE);
    
        }
    
        public static void witerAdapter(SelectionKey selectionKey) throws Exception{
            SocketChannel channel = (SocketChannel)selectionKey.channel();
    
            byteBuffer.clear();
            byteBuffer.put("收到消息了".getBytes());
            byteBuffer.flip();
    
            channel.write(byteBuffer);
    
            channel.register(selector,SelectionKey.OP_READ);
    
        }
    }
    
    
    

    客户端

    
    package socketnio;
    
    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.Scanner;
    import java.util.Set;
    
    public class NioSocketClient {
        static Selector selector = null;
    
        public static void main(String[] args)throws Exception {
    
            Scanner scanner = new Scanner(System.in);
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
    
            selector = Selector.open();
    
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
    
    
            socketChannel.connect(new InetSocketAddress("127.0.0.1",9999));
    
    
    
            while (true){
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
    
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey next = iterator.next();
    
                    if (next.isConnectable()){
                        System.out.println("开始客户端链接");
                        socketChannel.finishConnect();
                        socketChannel.register(selector,SelectionKey.OP_WRITE);
                    }else if (next.isWritable()){
                        System.out.println("请输入要发送的信息:");
                        String result = scanner.next();
    
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        byteBuffer.put(result.getBytes());
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
    
                        socketChannel.register(selector,SelectionKey.OP_READ);
                        System.out.println("结束~!!!~~~~");
                    }else if (next.isReadable()){
                        System.out.print("服务端返回的消息:");
                        int c = 0;
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        StringBuffer stringBuffer = new StringBuffer();
                        int read = socketChannel.read(byteBuffer);
                        System.out.println(new String(byteBuffer.array(),0,read));
                        socketChannel.register(selector,SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:nio实现socket

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