java.nio.channels.UnsupportedAddressTypeException#java.nio.channels.DatagramChannel源码实例Demo

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

源代码1 项目: mldht   文件: OpentrackerLiveSync.java
@Override
public void start(Collection<DHT> dhts, ConfigReader config) {
	try {
		channel = DatagramChannel.open(StandardProtocolFamily.INET);
		channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, 1);
		channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		// we only need to send, not to receive, so need to bind to a specific port
		channel.bind(new InetSocketAddress(0));
		channel.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {(byte) 224,0,23,5}), 9696));
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}
	
	t.setDaemon(true);
	t.setName("opentracker-sync");
	t.start();
	
	// OT-sync only supports ipv4 atm
	dhts.stream().filter(d -> d.getType().PREFERRED_ADDRESS_TYPE == Inet4Address.class).forEach(d -> {
		d.addIncomingMessageListener(this::incomingPacket);
	});

}
 
源代码2 项目: codeone2019-java-profiling   文件: DatagramTest.java
public static void main(String[] args) throws Exception {
    ch = DatagramChannel.open();
    ch.bind(new InetSocketAddress(5555));
    ch.configureBlocking(false);

    Executor pool = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        pool.execute(DatagramTest::sendLoop);
    }

    System.out.println("Warming up...");
    Thread.sleep(3000);
    totalPackets.set(0);

    System.out.println("Benchmarking...");
    Thread.sleep(5000);
    System.out.println(totalPackets.get() / 5);

    System.exit(0);
}
 
源代码3 项目: openjdk-jdk9   文件: 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();
}
 
protected void configureListenerChannel() {

        // open the listener port
        try {
            listenerChannel = DatagramChannel.open();
            listenerChannel.socket().bind(new InetSocketAddress(listenerPort));
            listenerChannel.configureBlocking(false);

            logger.info("Listening for incoming data on {}", listenerChannel.getLocalAddress());

            synchronized (selector) {
                selector.wakeup();
                try {
                    listenerKey = listenerChannel.register(selector, listenerChannel.validOps());
                } catch (ClosedChannelException e1) {
                    logger.warn("An exception occurred while registering a selector: {}", e1.getMessage());
                }
            }
        } catch (Exception e3) {
            logger.warn("An exception occurred while creating the Listener Channel on port number {} ({})",
                    listenerPort, e3.getMessage());
        }
    }
 
源代码5 项目: mts   文件: DatagramReactor.java
public void open(SocketAddress localSocketAddress, DatagramHandler handler) throws Exception
  {
      // Create a non-blocking socket channel
      DatagramChannel channel = DatagramChannel.open();
// read all properties for the UDP socket 
Config.getConfigForUDPSocket(channel.socket());

      channel.socket().bind(localSocketAddress);
      channel.configureBlocking(false);

      synchronized(selectorLock)
      {
          this.selector.wakeup();
          handler.init(channel.register(selector, SelectionKey.OP_READ, handler));
      }
  }
 
源代码6 项目: TencentKona-8   文件: 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();
}
 
源代码7 项目: 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();
}
 
源代码8 项目: TarsJava   文件: Server.java
protected void startNIOServer() throws Exception {
    SelectableChannel server = null;
    int interestKey;

    //1. Start reactor service
    selectorManager.start();

    //2. Start server on the specified port
    if (this.udpMode) {
        server = DatagramChannel.open();
        ((DatagramChannel) server).socket().bind(new InetSocketAddress(host, port));
        interestKey = SelectionKey.OP_READ;
    } else {
        server = ServerSocketChannel.open();
        ((ServerSocketChannel) server).socket().bind(new InetSocketAddress(host, port), 1024);
        interestKey = SelectionKey.OP_ACCEPT;

    }

    server.configureBlocking(false);

    //3. Choose one reactor to handle NIO event
    selectorManager.getReactor(0).registerChannel(server, interestKey);
    System.out.println("INFO: NAMI Server started on port " + String.valueOf(port) + "...");

}
 
源代码9 项目: android-netty   文件: SocketSendBufferPool.java
public long transferTo(DatagramChannel ch, SocketAddress raddr) throws IOException {
    int send = 0;
    for (ByteBuffer buf: buffers) {
        if (buf.hasRemaining()) {
            int w = ch.send(buf, raddr);
            if (w == 0) {
                break;
            } else {
                send += w;
            }
        }
    }
    written += send;

    return send;
}
 
源代码10 项目: j2objc   文件: DatagramChannelTest.java
public void testReadWrite_Block_WriterNotBound() throws Exception {
    byte[] sourceArray = new byte[CAPACITY_NORMAL];
    byte[] targetArray = new byte[CAPACITY_NORMAL];
    for (int i = 0; i < sourceArray.length; i++) {
        sourceArray[i] = (byte) i;
    }

    DatagramChannel dc = DatagramChannel.open();
    // The writer isn't bound, but is connected.
    dc.connect(channel1Address);

    // write
    ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
    assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));

    // Connect channel2 after data has been written.
    channel2.connect(dc.socket().getLocalSocketAddress());

    // read
    ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
    closeBlockedReaderChannel2(targetBuf);

    dc.close();
}
 
源代码11 项目: localization_nifi   文件: DatagramChannelSender.java
@Override
public void open() throws IOException {
    if (channel == null) {
        channel = DatagramChannel.open();

        if (maxSendBufferSize > 0) {
            channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize);
            final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF);
            if (actualSendBufSize < maxSendBufferSize) {
                logger.warn("Attempted to set Socket Send Buffer Size to " + maxSendBufferSize
                        + " bytes but could only set to " + actualSendBufSize + "bytes. You may want to "
                        + "consider changing the Operating System's maximum receive buffer");
            }
        }
    }

    if (!channel.isConnected()) {
        channel.connect(new InetSocketAddress(InetAddress.getByName(host), port));
    }
}
 
源代码12 项目: jdk8u-dev-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();
}
 
源代码13 项目: wildfly-core   文件: SocketBindingManagerImpl.java
/** {@inheritDoc} */
@Override
public Closeable registerChannel(String name, DatagramChannel channel) {
    final ManagedBinding binding = new CloseableManagedBinding(name, (InetSocketAddress) channel.socket().getLocalSocketAddress(), channel, this);
    registerBinding(binding);
    return binding;
}
 
源代码14 项目: Tomcat7.0.67   文件: NioReplicationTask.java
/**
 * send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
 * that it should always go to the buffer
 * @param key
 * @param channel
 */
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
    try {

        ByteBuffer buf = ByteBuffer.wrap(command);
        int total = 0;
        if (channel instanceof DatagramChannel) {
            DatagramChannel dchannel = (DatagramChannel)channel;
            //were using a shared channel, document says its thread safe
            //TODO check optimization, one channel per thread?
            while ( total < command.length ) {
                total += dchannel.send(buf, udpaddr);
            }
        } else {
            while ( total < command.length ) {
                total += channel.write(buf);
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("ACK sent to " +
                    ( (channel instanceof SocketChannel) ?
                      ((SocketChannel)channel).socket().getInetAddress() :
                      ((DatagramChannel)channel).socket().getInetAddress()));
        }
    } catch ( java.io.IOException x ) {
        log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
    }
}
 
源代码15 项目: hottub   文件: ChangingAddress.java
public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    SocketAddress remote = new InetSocketAddress(lh, 1234);

    DatagramSocket ds = null;
    DatagramChannel dc = null;
    try {

        ds = new DatagramSocket();
        dc = DatagramChannel.open().bind(new InetSocketAddress(0));
        check(ds, dc);

        ds.connect(remote);
        dc.connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.disconnect();
        check(ds, dc);

        // repeat tests using socket adapter
        ds.connect(remote);
        dc.socket().connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.socket().disconnect();
        check(ds, dc);

   } finally {
        if (ds != null) ds.close();
        if (dc != null) dc.close();
   }
}
 
源代码16 项目: gnirehtet   文件: UDPConnection.java
private DatagramChannel createChannel() throws IOException {
    logi(TAG, "Open");
    DatagramChannel datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.connect(getRewrittenDestination());
    return datagramChannel;
}
 
源代码17 项目: phoebus   文件: Network.java
/** Create UDP channel
 *
 *  @param broadcast Support broadcast?
 *  @param port Port to use or 0 to auto-assign
 *  @return UDP channel
 *  @throws Exception on error
 */
public static DatagramChannel createUDP(boolean broadcast, int port) throws Exception
{
    // Current use of multicast addresses works only with INET, not INET6
    final DatagramChannel udp = DatagramChannel.open(StandardProtocolFamily.INET);
    udp.configureBlocking(true);
    if (broadcast)
        udp.socket().setBroadcast(true);
    udp.socket().setReuseAddress(true);
    udp.bind(new InetSocketAddress(port));
    return udp;
}
 
源代码18 项目: openjdk-jdk9   文件: ChangingAddress.java
public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    SocketAddress remote = new InetSocketAddress(lh, 1234);

    DatagramSocket ds = null;
    DatagramChannel dc = null;
    try {

        ds = new DatagramSocket();
        dc = DatagramChannel.open().bind(new InetSocketAddress(0));
        check(ds, dc);

        ds.connect(remote);
        dc.connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.disconnect();
        check(ds, dc);

        // repeat tests using socket adapter
        ds.connect(remote);
        dc.socket().connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.socket().disconnect();
        check(ds, dc);

   } finally {
        if (ds != null) ds.close();
        if (dc != null) dc.close();
   }
}
 
源代码19 项目: netty4.0.27Learn   文件: NioDatagramChannel.java
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
    DatagramChannel ch = javaChannel();
    return ch.isOpen() && (
            config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
            || ch.socket().isBound());
}
 
源代码20 项目: dragonwell8_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();
}
 
源代码21 项目: jMAVSim   文件: UDPMavLinkPort.java
public void open(SocketAddress bindAddress, SocketAddress peerAddress) throws IOException {
    channel = DatagramChannel.open();
    channel.socket().bind(bindAddress);
    channel.configureBlocking(false);
    channel.connect(peerAddress);
    stream = new MAVLinkStream(schema, channel);
    stream.setDebug(debug);
}
 
源代码22 项目: netty-4.1.22   文件: NioDatagramChannel.java
private static DatagramChannel newSocket(SelectorProvider provider) {
    try {
        /**
         *  Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
         *  {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
         *
         *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
         */
        return provider.openDatagramChannel();
    } catch (IOException e) {
        throw new ChannelException("Failed to open a socket.", e);
    }
}
 
源代码23 项目: netty-4.1.22   文件: NioDatagramChannel.java
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
    DatagramChannel ch = javaChannel();
    return ch.isOpen() && (
            config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
            || ch.socket().isBound());
}
 
public ArrayList<Channel> getAll(Direction direction, DatagramChannel theDatagramChannel) {
    synchronized (this) {
        ArrayList<Channel> selectedChannels = new ArrayList<Channel>();

        Iterator<C> it = iterator();
        while (it.hasNext()) {
            C aChannel = it.next();
            if (theDatagramChannel.equals(aChannel.channel) && direction.equals(aChannel.direction)) {
                selectedChannels.add(aChannel);
            }
        }

        return selectedChannels;
    }
}
 
源代码25 项目: netty-4.1.22   文件: NioDatagramChannel.java
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannel ch = javaChannel();
    DatagramChannelConfig config = config();
    RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();

    ByteBuf data = allocHandle.allocate(config.getAllocator());
    allocHandle.attemptedBytesRead(data.writableBytes());
    boolean free = true;
    try {
        ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
        int pos = nioData.position();
        InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
        if (remoteAddress == null) {
            return 0;
        }

        allocHandle.lastBytesRead(nioData.position() - pos);
        buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()),
                localAddress(), remoteAddress));
        free = false;
        return 1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    }  finally {
        if (free) {
            data.release();
        }
    }
}
 
源代码26 项目: Voovan   文件: UdpSocket.java
/**
 * 构造函数
 * @param parentSocketContext 父 SocketChannel 对象
 * @param datagramChannel UDP通信对象
 * @param socketAddress SocketAddress 对象
 */
public UdpSocket(SocketContext parentSocketContext, DatagramChannel datagramChannel, InetSocketAddress socketAddress){
    try {
        this.provider = SelectorProvider.provider();
        this.datagramChannel = datagramChannel;
        this.copyFrom(parentSocketContext);
        this.session = new UdpSession(this, socketAddress);
        this.datagramChannel.configureBlocking(false);
        this.connectModel = ConnectModel.SERVER;
        this.connectType = ConnectType.UDP;
    } catch (Exception e) {
        Logger.error("Create socket channel failed",e);
    }
}
 
源代码27 项目: jdk8u-dev-jdk   文件: ChangingAddress.java
public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    SocketAddress remote = new InetSocketAddress(lh, 1234);

    DatagramSocket ds = null;
    DatagramChannel dc = null;
    try {

        ds = new DatagramSocket();
        dc = DatagramChannel.open().bind(new InetSocketAddress(0));
        check(ds, dc);

        ds.connect(remote);
        dc.connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.disconnect();
        check(ds, dc);

        // repeat tests using socket adapter
        ds.connect(remote);
        dc.socket().connect(remote);
        check(ds, dc);

        ds.disconnect();
        dc.socket().disconnect();
        check(ds, dc);

   } finally {
        if (ds != null) ds.close();
        if (dc != null) dc.close();
   }
}
 
public void replace(Direction direction, InetSocketAddress remoteAddress, DatagramChannel channel) {
    synchronized (this) {
        Iterator<C> it = iterator();
        while (it.hasNext()) {
            C aChannel = it.next();
            if (remoteAddress.equals(aChannel.remote) && direction.equals(aChannel.direction)
                    && !channel.equals(aChannel.channel)) {
                aChannel.channel = channel;
            }
        }
    }
}
 
源代码29 项目: perfmon-agent   文件: PerfMonMetricGetterTest.java
public void testProcessNextCommand() throws Exception {
    System.out.println("processNextCommand");
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), DatagramChannel.open());
    boolean expResult = false;
    boolean result = instance.processNextCommand();
    assertEquals(expResult, result);
}
 
源代码30 项目: j2objc   文件: DatagramChannelTest.java
public void test_bind_null() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    try {
        assertNull(dc.socket().getLocalSocketAddress());

        dc.socket().bind(null);

        InetSocketAddress localAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
        assertTrue(localAddress.getAddress().isAnyLocalAddress());
        assertTrue(localAddress.getPort() > 0);
    } finally {
        dc.close();
    }
}