zoukankan      html  css  js  c++  java
  • Java NIO -- DatagramChannel

    Java NIO中的DatagramChannel是一个能收发UDP包的通道。
    操作步骤:
    打开 DatagramChannel
    接收/发送数据

    代码举例:

    package com.soyoungboy.nio;
    
    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.Date;
    import java.util.Iterator;
    import java.util.Scanner;
    
    import org.junit.Test;
    
    public class TestDatagramChannel {
        
        @Test
        public void send() throws IOException{
            DatagramChannel dc = DatagramChannel.open();
            
            dc.configureBlocking(false);
            
            ByteBuffer buf = ByteBuffer.allocate(1024);
            
            Scanner scan = new Scanner(System.in);
            
            while(scan.hasNext()){
                String str = scan.next();
                buf.put((new Date().toString() + ":
    " + str).getBytes());
                buf.flip();
                dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));
                buf.clear();
            }
            
            dc.close();
        }
        
        @Test
        public void receive() throws IOException{
            DatagramChannel dc = DatagramChannel.open();
            
            dc.configureBlocking(false);
            
            dc.bind(new InetSocketAddress(9898));
            
            Selector selector = Selector.open();
            
            dc.register(selector, SelectionKey.OP_READ);
            
            while(selector.select() > 0){
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                
                while(it.hasNext()){
                    SelectionKey sk = it.next();
                    
                    if(sk.isReadable()){
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        
                        dc.receive(buf);
                        buf.flip();
                        System.out.println(new String(buf.array(), 0, buf.limit()));
                        buf.clear();
                    }
                }
                
                it.remove();
            }
        }
    
    }
  • 相关阅读:
    常见的网络设备:集线器 hub、网桥、交换机 switch、路由器 router、网关 gateway
    Linux 路由表详解及 route 命令详解
    Flannel
    Flannel
    Hugo
    Nginx 实现全站 HTTPS(基于 Let's Encrypt 的免费通配符证书)
    Nginx 安装
    ETCD 简介及基本用法
    Vagrant 手册之 Multi-machine 多机器
    Vagrant 手册之 Provisioning
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/7087046.html
Copyright © 2011-2022 走看看