java.nio.channels.DatagramChannel#open()源码实例Demo

下面列出了java.nio.channels.DatagramChannel#open() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-8-source   文件: UseDGWithIPv6.java
public static void main(String[] args) throws IOException
{
    ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
    DatagramChannel dgChannel = DatagramChannel.open();

    for(int i = 0; i < targets.length; i++){
        data.rewind();
        SocketAddress sa = new InetSocketAddress(targets[i], port);
        System.out.println("-------------\nDG_Sending data:" +
                           "\n    remaining:" + data.remaining() +
                           "\n     position:" + data.position() +
                           "\n        limit:" + data.limit() +
                           "\n     capacity:" + data.capacity() +
                           " bytes on DG channel to " + sa);
        try {
            int n = dgChannel.send(data, sa);
            System.out.println("DG_Sent " + n + " bytes");
        } catch (IOException e) {
            //This regression test is to check vm crash only, so ioe is OK.
            e.printStackTrace();
        }
    }
    dgChannel.close();
}
 
源代码2 项目: dragonwell8_jdk   文件: JdpBroadcaster.java
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
源代码3 项目: jdk8u-jdk   文件: UseDGWithIPv6.java
public static void main(String[] args) throws IOException
{
    ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
    DatagramChannel dgChannel = DatagramChannel.open();

    for(int i = 0; i < targets.length; i++){
        data.rewind();
        SocketAddress sa = new InetSocketAddress(targets[i], port);
        System.out.println("-------------\nDG_Sending data:" +
                           "\n    remaining:" + data.remaining() +
                           "\n     position:" + data.position() +
                           "\n        limit:" + data.limit() +
                           "\n     capacity:" + data.capacity() +
                           " bytes on DG channel to " + sa);
        try {
            int n = dgChannel.send(data, sa);
            System.out.println("DG_Sent " + n + " bytes");
        } catch (IOException e) {
            //This regression test is to check vm crash only, so ioe is OK.
            e.printStackTrace();
        }
    }
    dgChannel.close();
}
 
private void check() throws IOException {
    try (DatagramChannel channel = DatagramChannel.open()) {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        buffer.order(ByteOrder.BIG_ENDIAN);

        buffer.clear();
        buffer.flip();
        channel.send(buffer, LOCAL_ADDRESS);

        buffer.clear();
        channel.receive(buffer);

        buffer.flip();
        long seconds = Integer.toUnsignedLong(buffer.getInt());

        Calendar calendar = new GregorianCalendar(1900, Calendar.JANUARY, 1, 0, 0, 0);
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        long timeMs = calendar.getTimeInMillis() + seconds * 1000;

        Assert.assertTrue(Math.abs(System.currentTimeMillis() - timeMs) < 5000);
    }
}
 
源代码5 项目: j2objc   文件: DatagramChannelTest.java
public void test_send_LBuffer_LSocketAddress_PositionNotZero()
        throws Exception {
    // regression test for Harmony-701
    int CAPACITY_NORMAL = 256;
    int position = 16;
    DatagramChannel dc = DatagramChannel.open();
    byte[] sourceArray = new byte[CAPACITY_NORMAL];
    // send ByteBuffer whose position is not zero
    ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
    sourceBuf.position(position);
    int ret = dc.send(sourceBuf, datagramSocket1Address);
    // assert send (256 - 16) bytes
    assertEquals(CAPACITY_NORMAL - position, ret);
    // assert the position of ByteBuffer has been set
    assertEquals(CAPACITY_NORMAL, sourceBuf.position());
}
 
源代码6 项目: bt   文件: AddressUtils.java
public static InetAddress getDefaultRoute(Class<? extends InetAddress> type) {
	InetAddress target = null;
	
	ProtocolFamily family = type == Inet6Address.class ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
	
	try(DatagramChannel chan=DatagramChannel.open(family)) {
		if(type == Inet4Address.class)
			target = InetAddress.getByAddress(new byte[] {8,8,8,8});
		if(type == Inet6Address.class)
			target = InetAddress.getByName("2001:4860:4860::8888");
		
		chan.connect(new InetSocketAddress(target,63));
		
		InetSocketAddress soa = (InetSocketAddress) chan.getLocalAddress();
		InetAddress local = soa.getAddress();
		
		if(type.isInstance(local) && !local.isAnyLocalAddress())
			return local;
		return null;
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}
 
源代码7 项目: jdk8u60   文件: UseDGWithIPv6.java
public static void main(String[] args) throws IOException
{
    ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
    DatagramChannel dgChannel = DatagramChannel.open();

    for(int i = 0; i < targets.length; i++){
        data.rewind();
        SocketAddress sa = new InetSocketAddress(targets[i], port);
        System.out.println("-------------\nDG_Sending data:" +
                           "\n    remaining:" + data.remaining() +
                           "\n     position:" + data.position() +
                           "\n        limit:" + data.limit() +
                           "\n     capacity:" + data.capacity() +
                           " bytes on DG channel to " + sa);
        try {
            int n = dgChannel.send(data, sa);
            System.out.println("DG_Sent " + n + " bytes");
        } catch (IOException e) {
            //This regression test is to check vm crash only, so ioe is OK.
            e.printStackTrace();
        }
    }
    dgChannel.close();
}
 
源代码8 项目: gnirehtet   文件: UDPConnection.java
private DatagramChannel createChannel() throws IOException {
    logi(TAG, "Open");
    DatagramChannel datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.connect(getRewrittenDestination());
    return datagramChannel;
}
 
源代码9 项目: openjdk-jdk9   文件: NotBound.java
static void wakeupWhenBound(final DatagramChannel dc) {
    Runnable wakeupTask = new Runnable() {
        public void run() {
            try {
                // poll for local address
                InetSocketAddress local;
                do {
                    Thread.sleep(50);
                    local = (InetSocketAddress)dc.getLocalAddress();
                } while (local == null);

                // send message to channel to wakeup receiver
                DatagramChannel sender = DatagramChannel.open();
                try {
                    ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
                    InetAddress lh = InetAddress.getLocalHost();
                    SocketAddress target =
                        new InetSocketAddress(lh, local.getPort());
                    sender.send(bb, target);
                } finally {
                    sender.close();
                }

            } catch (Exception x) {
                x.printStackTrace();
            }
        }};
    new Thread(wakeupTask).start();
}
 
源代码10 项目: j2objc   文件: FileChannelTest.java
/**
 * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
 */
public void test_transferFromLReadableByteChannelJJ_NonWritable()
        throws Exception {
    readByteChannel = DatagramChannel.open();
    try {
        readOnlyFileChannel.transferFrom(readByteChannel, 0, 0);
        fail("should throw NonWritableChannelException.");
    } catch (NonWritableChannelException e) {
        // expected
    }
}
 
源代码11 项目: j2objc   文件: DatagramChannelTest.java
public void testSocket_NonBlock_BasicStatusAfterConnect() throws IOException {
    final DatagramChannel dc = DatagramChannel.open();
    dc.connect(datagramSocket1Address);
    dc.configureBlocking(false);

    DatagramSocket s1 = dc.socket();
    assertSocketAfterConnect(s1);
    DatagramSocket s2 = dc.socket();
    // same
    assertSame(s1, s2);

    dc.close();
}
 
源代码12 项目: perfmon-agent   文件: TransportFactory.java
/**
 * @param addr
 * @return transport instance
 * @throws IOException
 * @deprecated because of instability
 */
public static Transport NIOUDPInstance(SocketAddress addr) throws IOException {
    DatagramChannel channel = DatagramChannel.open();
    channel.connect(addr);

    NIOTransport ret = new NIOTransport();
    ret.setChannels(channel, channel);
    return ret;
}
 
源代码13 项目: Tomcat7.0.67   文件: NioReceiver.java
protected void bind() throws IOException {
    // allocate an unbound server socket channel
    serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        this.selector.set(Selector.open());
    }
    // set the port the server channel will listen to
    //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort()));
    bind(serverSocket,getPort(),getAutoBind());
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(this.selector.get(), SelectionKey.OP_ACCEPT);

    //set up the datagram channel
    if (this.getUdpPort()>0) {
        datagramChannel = DatagramChannel.open();
        configureDatagraChannel();
        //bind to the address to avoid security checks
        bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind());
    }
}
 
源代码14 项目: perfmon-agent   文件: PerfMonMetricGetterTest.java
public void testSendMetrics() throws IOException {
    System.out.println("sendMetrics");
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), DatagramChannel.open());
    instance.getMetricsLine();
}
 
源代码15 项目: jdk8u-jdk   文件: NotBound.java
static void wakeupWhenBound(final DatagramChannel dc) {
    Runnable wakeupTask = new Runnable() {
        public void run() {
            try {
                // poll for local address
                InetSocketAddress local;
                do {
                    Thread.sleep(50);
                    local = (InetSocketAddress)dc.getLocalAddress();
                } while (local == null);

                // send message to channel to wakeup receiver
                DatagramChannel sender = DatagramChannel.open();
                try {
                    ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
                    InetAddress lh = InetAddress.getLocalHost();
                    SocketAddress target =
                        new InetSocketAddress(lh, local.getPort());
                    sender.send(bb, target);
                } finally {
                    sender.close();
                }

            } catch (Exception x) {
                x.printStackTrace();
            }
        }};
    new Thread(wakeupTask).start();
}
 
源代码16 项目: craft-atom   文件: NioUdpAcceptor.java
@Override
protected void bindByProtocol(SocketAddress address) throws IOException {
	DatagramChannel dc = DatagramChannel.open();
	dc.configureBlocking(false);
	dc.socket().setReuseAddress(config.isReuseAddress());
	dc.socket().bind(address);
	boundmap.put(address, dc);
	
	NioByteChannel channel = new NioUdpByteChannel(dc, config, predictorFactory.newPredictor(config.getMinReadBufferSize(), config.getDefaultReadBufferSize(), config.getMaxReadBufferSize()), dispatcher);
	NioProcessor processor = pool.pick(channel);
	processor.setProtocol(IoProtocol.UDP);
	channel.setProcessor(processor);
	processor.add(channel);
}
 
源代码17 项目: jdk8u60   文件: NotBound.java
static void wakeupWhenBound(final DatagramChannel dc) {
    Runnable wakeupTask = new Runnable() {
        public void run() {
            try {
                // poll for local address
                InetSocketAddress local;
                do {
                    Thread.sleep(50);
                    local = (InetSocketAddress)dc.getLocalAddress();
                } while (local == null);

                // send message to channel to wakeup receiver
                DatagramChannel sender = DatagramChannel.open();
                try {
                    ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
                    InetAddress lh = InetAddress.getLocalHost();
                    SocketAddress target =
                        new InetSocketAddress(lh, local.getPort());
                    sender.send(bb, target);
                } finally {
                    sender.close();
                }

            } catch (Exception x) {
                x.printStackTrace();
            }
        }};
    new Thread(wakeupTask).start();
}
 
源代码18 项目: mr4c   文件: StatsdClient.java
public StatsdClient(InetAddress host, int port) throws IOException {
	_address = new InetSocketAddress(host, port);
	_channel = DatagramChannel.open();
               setBufferSize((short) 1500);
}
 
源代码19 项目: netcrusher-java   文件: EmptyDatagramTest.java
@Test
public void test() throws Exception {
    CyclicBarrier barrier = new CyclicBarrier(2);

    DatagramBulkReflector reflector = new DatagramBulkReflector("REFLECTOR", REFLECTOR_ADDRESS, 1, barrier);
    reflector.open();

    barrier.await();
    Thread.sleep(1000);

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(true);

    ByteBuffer bb = ByteBuffer.allocate(100);

    try {
        // sent
        bb.clear();
        bb.flip();
        int sent = channel.send(bb, CRUSHER_ADDRESS);
        Assert.assertEquals(0, sent);

        // check
        Thread.sleep(500);

        Assert.assertEquals(1, crusher.getClientTotalCount());

        RateMeters innerByteMeters = crusher.getInnerByteMeters();
        Assert.assertEquals(0, innerByteMeters.getReadMeter().getTotalCount());
        Assert.assertEquals(0, innerByteMeters.getSentMeter().getTotalCount());

        RateMeters innerPacketMeters = crusher.getInnerPacketMeters();
        Assert.assertEquals(1, innerPacketMeters.getReadMeter().getTotalCount());
        Assert.assertEquals(1, innerPacketMeters.getSentMeter().getTotalCount());

        // read
        bb.clear();
        InetSocketAddress address = (InetSocketAddress) channel.receive(bb);
        Assert.assertNotNull(address);
        Assert.assertEquals(CRUSHER_ADDRESS, address);
        Assert.assertEquals(0, bb.position());
    } finally {
        NioUtils.close(channel);
        NioUtils.close(reflector);
    }
}
 
源代码20 项目: TarsJava   文件: ServantClient.java
protected synchronized void reConnect() throws IOException {
    if (isNotConnected()) {
        SocketAddress server = new InetSocketAddress(this.host, this.port);
        SelectableChannel channel = null;
        Session temp = null;
        int event;

        if (this.udpMode) {
            channel = DatagramChannel.open();
            channel.configureBlocking(false);

            temp = new UDPSession(this.selectorManager);
            ((UDPSession) temp).setBufferSize(bufferSize);
            ((UDPSession) temp).setTarget(server);
            event = SelectionKey.OP_READ;
            temp.setStatus(SessionStatus.CLIENT_CONNECTED);
        } else {
            channel = SocketChannel.open();
            channel.configureBlocking(false);
            try {
                if (this.tc != INVALID_TRAFFIC_CLASS_VALUE) {
                    ((SocketChannel) channel).socket().setTrafficClass(this.tc);
                }
            } catch (Exception ex) {
                logger.error(ex.getLocalizedMessage());
            }
            ((SocketChannel) channel).connect(server);

            temp = new TCPSession(this.selectorManager);
            ((TCPSession) temp).setTcpNoDelay(this.tcpNoDelay);
            event = SelectionKey.OP_CONNECT;
        }

        temp.setChannel(channel);
        temp.setKeepAlive(selectorManager.isKeepAlive());

        this.selectorManager.nextReactor().registerChannel(channel, event, temp);

        if (!this.udpMode) {
            if (!temp.waitToConnect(this.connectTimeout)) {
                temp.asyncClose();
                throw new TimeoutException("connect " + this.connectTimeout + "ms timed out to " + this.getAddress());
            }

            if (temp.getStatus() == SessionStatus.NOT_CONNECTED) {
                temp.asyncClose();
                throw new NotConnectedException("connect failed to " + this.getAddress());
            } else if (temp.getStatus() == SessionStatus.CLOSED) {
                throw new NotConnectedException("connect failed to " + this.getAddress());
            }
        }
        this.session = temp;
    }
}