TestPipe

public class TestPipe  {

    @Test
    public void test()throws Exception{
        Pipe pipe = Pipe.open();
        final Pipe.SinkChannel sinkChannel = pipe.sink();
        final Pipe.SourceChannel sourceChannel = pipe.source();
        Thread t1 = new Thread(){
            @Override
            public void run(){
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.put("大家好呀呀哎呀".getBytes());
                    buffer.flip();
                    sinkChannel.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t2 =new Thread(){
            @Override
            public void run() {
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = sourceChannel.read(buffer);
                    buffer.flip();
                    System.out.println("接收到:"+new String(buffer.array(),0,len));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        t1.start();
        t2.start();
    }

    @Test
    public void send()throws Exception{
        Pipe pipe = Pipe.open();

        Pipe.SinkChannel sinkChannel = pipe.sink();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("大家好".getBytes());
        buffer.flip();
        sinkChannel.write(buffer);

        Pipe.SourceChannel sourceChannel = pipe.source();
        sourceChannel.read(buffer);
        buffer.flip();
        System.out.println(new String(buffer.array(),0,buffer.limit()));
    }
}

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