TestDatagramChannel

public class TestDatagramChannel {

    @Test
    public void send()throws Exception{
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String message = scanner.next();
            buffer.put((new Date().toString()+":\n"+message).getBytes());
            buffer.flip();
            datagramChannel.send(buffer,new InetSocketAddress("127.0.0.1",9897));
            buffer.clear();
        }

        datagramChannel.close();
    }

    @Test
    public void receive()throws Exception{
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.bind(new InetSocketAddress(9897));
        datagramChannel.configureBlocking(false);

        Selector selector = Selector.open();
        datagramChannel.register(selector, SelectionKey.OP_READ);

        while (selector.select()>0){
            Iterator iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isReadable()){
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    datagramChannel.receive(buffer);
                    buffer.flip();
                    System.out.println(new String(buffer.array(),0,buffer.limit()));
                }

                iterator.remove();
            }
        }
    }
}

你可能感兴趣的:(JAVA,java,开发语言,后端)