java nio多终端聊天小案例

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();
    }
}

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

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1 背景 1.1 简介 java.nio 全称 java non-blocking IO,是指jdk1.4 及以上...
    龙腾四海365阅读 353评论 0赞 1
  • Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java I...
    JackChen1024阅读 8,078评论 1赞 143
  • Java NIO指JDK 1.4中提供的新IO,可以理解为非阻塞IO(non-blocking IO),为所有的原...
    简单一点点阅读 1,563评论 0赞 0
  • 那是我永远学不会的专注的温柔。 感觉都好美啊!
    CNBLUEone阅读 173评论 0赞 0
  • 过年的气氛愈加浓厚,老爸老妈也忙里忙外。老妈是孩子生意家里双手齐开,身体还是垮了,看着上吐下泄一整晚,要不是大姐提...
    诗简舒阅读 287评论 0赞 0

友情链接更多精彩内容