使用Channel、Buffer、Selector完成网络通信--非阻塞(二)
来源:互联网 发布:阿里云电话人工服务 编辑:程序博客网 时间:2024/05/01 10:25
发送端
public void send() throws IOException{DatagramChannel dc = DatagramChannel.open();//获取通道dc.configureBlocking(false);//切换非阻塞模式ByteBuffer byteBuffer = ByteBuffer.allocate(1024);Scanner scanner = new Scanner(System.in);while(scanner.hasNext()){String data = scanner.next();byteBuffer.put((LocalDateTime.now().toString()+"\n"+data).getBytes());byteBuffer.flip();dc.send(byteBuffer,new InetSocketAddress("127.0.0.1",8989));byteBuffer.clear();}dc.close();}
接收端
public void receive() throws IOException{DatagramChannel dc = DatagramChannel.open(); //获取通道dc.configureBlocking(false); //切换非阻塞模式dc.bind(new InetSocketAddress(8989)); //绑定端口Selector selector =Selector.open(); //获取选择器dc.register(selector,SelectionKey.OP_READ); //将通道注册到选择器中while(selector.select() > 0){ //轮询获取选择器上准备就绪的状态Iterator<SelectionKey> it = selector.selectedKeys().iterator(); //获取选择器中所有注册的选择键while(it.hasNext()){SelectionKey selectionKey =it.next(); //获取就绪的事件if(selectionKey.isReadable()){ //判断是否为读取事件、然后读取ByteBuffer buffer = ByteBuffer.allocate(1024);dc.receive(buffer);buffer.flip();System.out.println(new String(buffer.array(),0,buffer.limit()));buffer.clear();}}it.remove();//取消选择键}}
阅读全文
0 0
- 使用Channel、Buffer、Selector完成网络通信--非阻塞(二)
- 使用Channel、Buffer、Selector完成网络通信--非阻塞(一)
- 关于NIO笔记(四):非阻塞式网络通信核心之选择器(Selector)
- java nio 非阻塞要点 Selector(二)
- 非阻塞式网络通信
- Windows网络编程之(二)Socket通信非阻塞模式Select(TCP和UDP)
- 使用NIO实现非阻塞式的网络通信
- NIO基础(3)-非阻塞式网络通信
- JAVA NIO : Buffer ,Channel, Selector,Pipe
- NIO中Channel、Buffer、Selector详解
- JAVA NIO : Buffer ,Channel, Selector,Pipe
- NIO之二(Buffer&&Selector)
- 网络通信之同步异步阻塞非阻塞
- Linux 网络编程二:非阻塞select
- 使用非阻塞方式的Socket通信
- 使用非阻塞通信的简单聊天工具
- 使用NIO实现非阻塞Socket通信
- 使用NIO实现非阻塞Socket通信
- StringEscapeUtils的常用使用,防止SQL注入及XSS注入
- linux 网速监测工具
- ionic练习(1)- 实现页面切换
- @PostConstruct 和@PreDestory
- julianDate与Date之间的转换关系
- 使用Channel、Buffer、Selector完成网络通信--非阻塞(二)
- SQLite数据库详解
- java最基础
- TensorFlow入门
- git diff与patch命令的配合使用
- Spring JdbcTemplate 与 事务管理 学习
- Faster RCNN
- MyBatis学习总结(七)——Mybatis缓存
- 分布式锁的几种实现方式