美文网首页
java nio多终端聊天小案例

java nio多终端聊天小案例

作者: small瓜瓜 | 来源:发表于2019-06-03 11:22 被阅读0次

    java.nio全称java non-blocking IO,是指jdk1.4 及以上版本里提供的新api(New IO) ,为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,使用它可以提供非阻塞式的高伸缩性网络。

    官方文档

    TCP多终端聊天小案例 UDP多终端聊天小案例

    下面是一个基于TCP的多终端聊天小案例

    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.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    
    public class Server {
        public static void main(String[] args) throws IOException {
            server();
        }
    
        private static void server() throws IOException {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
    
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
    
            while (selector.select() > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    if (next.isAcceptable()) {
                        System.out.println("有新连接");
                        SocketChannel accept =  ssc.accept();
                        accept.configureBlocking(false);
                        accept.register(selector,SelectionKey.OP_READ);
                    } else if (next.isReadable()) {
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer bb = ByteBuffer.allocate(1024);
                        int len;
                        StringBuffer sb = new StringBuffer();
                        while((len = channel.read(bb)) != 0){
                            bb.flip();
                            sb.append(new String(bb.array(),0,len));
                            bb.clear();
                        }
                        System.out.println(sb.toString());
                    }
                    iterator.remove();
                }
            }
        }
    }
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SocketChannel;
    import java.util.Scanner;
    
    public class Client {
        public static void main(String[] args) throws IOException {
            client();
        }
    
        static void client() throws IOException {
            SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
            sc.configureBlocking(false);
            ByteBuffer bb = ByteBuffer.allocate(1024);
    
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String s = scanner.nextLine();
                bb.put(s.getBytes());
                bb.flip();
                sc.write(bb);
                bb.clear();
            }
            scanner.close();
            sc.close();
        }
    }
    

    下面是一个基于UDP的多终端聊天小案例

    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.DatagramChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.util.Iterator;
    
    public class Server {
       public static void main(String[] args) throws IOException {
           DatagramChannel dc = DatagramChannel.open();
           dc.configureBlocking(false);
    
           dc.bind(new InetSocketAddress(8080));
    
           Selector selector = Selector.open();
           dc.register(selector, SelectionKey.OP_READ);
    
           while (selector.select() > 0) {
               Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
               while (iterator.hasNext()) {
                   SelectionKey next = iterator.next();
                   if (next.isReadable()) {
                       DatagramChannel channel = (DatagramChannel) next.channel();
                       ByteBuffer buffer = ByteBuffer.allocate(1024);
                       channel.receive(buffer);
                       buffer.flip();
                       System.out.println(new String(buffer.array(), 0, buffer.limit()));
                   }
                   iterator.remove();
               }
           }
       }
    }
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.DatagramChannel;
    import java.util.Scanner;
    
    public class Client {
        public static void main(String[] args) throws IOException {
            DatagramChannel dc = DatagramChannel.open();
            dc.configureBlocking(false);
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                allocate.put(scanner.nextLine().getBytes());
                allocate.flip();
                dc.send(allocate, new InetSocketAddress("127.0.0.1", 8080));
                allocate.clear();
            }
            dc.close();
        }
    }
    

    功能很简陋,主要是提供给初学者一点小帮助,如果代码有误,还请大佬们指正

    相关文章

      网友评论

          本文标题:java nio多终端聊天小案例

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