Java Code Examples for java.nio.channels.DatagramChannel#configureBlocking()

The following examples show how to use java.nio.channels.DatagramChannel#configureBlocking() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestNonBlockingNIO2.java    From code with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 2
Source File: UdpBioProtocolServer.java    From redkale with Apache License 2.0 6 votes vote down vote up
@Override
public void open(AnyValue config) throws IOException {
    DatagramChannel ch = DatagramChannel.open();
    ch.configureBlocking(true);
    this.serverChannel = ch;
    final Set<SocketOption<?>> options = this.serverChannel.supportedOptions();
    if (options.contains(StandardSocketOptions.TCP_NODELAY)) {
        this.serverChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    }
    if (options.contains(StandardSocketOptions.SO_KEEPALIVE)) {
        this.serverChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
    }
    if (options.contains(StandardSocketOptions.SO_REUSEADDR)) {
        this.serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    }
    if (options.contains(StandardSocketOptions.SO_RCVBUF)) {
        this.serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    }
    if (options.contains(StandardSocketOptions.SO_SNDBUF)) {
        this.serverChannel.setOption(StandardSocketOptions.SO_SNDBUF, 16 * 1024);
    }
}
 
Example 3
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 6 votes vote down vote up
public void testProcessCommand() throws IOException {
    System.out.println("processCommand");
    String toString = "test\ntest\nerr\n";
    final DatagramChannel channel = DatagramChannelEmul.open();
    channel.configureBlocking(false);
    final InetSocketAddress inetSocketAddress = new InetSocketAddress(
            "localhost", 4444);
    channel.connect(inetSocketAddress);
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), channel, inetSocketAddress);
    instance.addCommandString(toString);
    instance.processNextCommand();
    instance.processNextCommand();
    try {
        instance.processNextCommand();
        fail();
    } catch (UnsupportedOperationException e) {
    }
}
 
Example 4
Source File: NioDatagramAcceptor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected DatagramChannel open(SocketAddress localAddress) throws Exception {
    final DatagramChannel c = DatagramChannel.open();
    boolean success = false;
    try {
        new NioDatagramSessionConfig(c).setAll(getSessionConfig());
        c.configureBlocking(false);
        c.socket().bind(localAddress);
        c.register(selector, SelectionKey.OP_READ);
        success = true;
    } finally {
        if (!success) {
            close(c);
        }
    }

    return c;
}
 
Example 5
Source File: DatagramReactor.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
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));
      }
  }
 
Example 6
Source File: UnknownPortDatagramTest.java    From netcrusher-java with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(true);
    channel.connect(new InetSocketAddress(HOSTNAME, PORT_CRUSHER));

    try {
        ByteBuffer bb = ByteBuffer.allocate(1024);
        bb.limit(800);
        bb.position(0);

        channel.write(bb);

        Thread.sleep(1001);
    } finally {
        NioUtils.close(channel);
    }
}
 
Example 7
Source File: MulticastTest.java    From mpush with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws Exception {
    String host = "239.239.239.99";//多播地址
    int port = 9999;
    InetAddress group = InetAddress.getByName(host);
    String message = "test-multicastSocket";

    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
    channel.configureBlocking(true);
    channel.bind(new InetSocketAddress(port));
    channel.join(group, Utils.getLocalNetworkInterface());

    InetSocketAddress sender = new InetSocketAddress("239.239.239.99", 4000);
    channel.send(ByteBuffer.wrap(message.getBytes()), sender);

    channel.close();
}
 
Example 8
Source File: NioUdpEventGroup.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected SelectableChannel __doChannelCreate(IServerCfg cfg) throws IOException {
    DatagramChannel _channel = DatagramChannel.open();
    _channel.configureBlocking(false);
    _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort()));
    return _channel;
}
 
Example 9
Source File: TestNonBlockingNIO2.java    From code with Apache License 2.0 5 votes vote down vote up
@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() + "\n" + str).getBytes());
        buf.flip();
        dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));
        buf.clear();
    }
    dc.close();
}
 
Example 10
Source File: EmptyDatagramTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoCrusher() throws Exception {
    CyclicBarrier barrier = new CyclicBarrier(2);

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

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(true);
    // No empty datagram for connected socket
    // https://bugs.openjdk.java.net/browse/JDK-8013175
    // channel.connect(reflectorAddress);

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

    ByteBuffer bb = ByteBuffer.allocate(0);

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

        // read
        bb.clear();
        InetSocketAddress address = (InetSocketAddress) channel.receive(bb);
        Assert.assertNotNull(address);
        Assert.assertEquals(REFLECTOR_ADDRESS, address);
        Assert.assertEquals(0, bb.position());
    } finally {
        NioUtils.close(channel);
        NioUtils.close(reflector);
    }
}
 
Example 11
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testNonBlockingRecv() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    try {
        dc.configureBlocking(false);
        dc.socket().bind(null);
        // Should return immediately, since we're non-blocking.
        assertNull(dc.receive(ByteBuffer.allocate(2048)));
    } finally {
        dc.close();
    }
}
 
Example 12
Source File: AnnounceGroupChannel.java    From bt with Apache License 2.0 5 votes vote down vote up
private synchronized DatagramChannel getChannel() throws IOException {
    if (channel == null || !channel.isOpen()) {
        if (shutdown.get()) {
            throw new IllegalStateException("Channel has been shut down");
        }
        ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
        DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
        _channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        // bind to any-local before setting TTL
        int port = group.getAddress().getPort();
        if (protocolFamily == StandardProtocolFamily.INET) {
            _channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
        } else {
            _channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
        }
        int timeToLive = group.getTimeToLive();
        if (timeToLive != 1) {
            _channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
        }

        for (NetworkInterface iface : networkInterfaces) {
            _channel.join(group.getAddress().getAddress(), iface);
        }

        _channel.configureBlocking(false);
        channel = _channel;
    }
    return channel;
}
 
Example 13
Source File: Network.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** 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;
}
 
Example 14
Source File: MoldUDP64.java    From nassau with Apache License 2.0 5 votes vote down vote up
/**
 * Receive messages. Invoke the message listener on each message. Continue
 * until a packet indicating the End of Session is received.
 *
 * @param multicastInterface the multicast interface
 * @param multicastGroup the multicast group
 * @param requestAddress the request address
 * @param listener a message listener
 * @throws IOException if an I/O error occurs
 */
public static void receive(NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
        MessageListener listener) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress(multicastGroup.getPort()));
    channel.join(multicastGroup.getAddress(), multicastInterface);
    channel.configureBlocking(false);

    DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);

    requestChannel.configureBlocking(false);

    StatusListener statusListener = new StatusListener();

    try (Selector selector = Selector.open();
            MoldUDP64Client client = new MoldUDP64Client(channel, requestChannel,
                requestAddress, listener, statusListener)) {
        SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ);

        SelectionKey requestChannelKey = requestChannel.register(selector, SelectionKey.OP_READ);

        while (statusListener.receive) {
            while (selector.select() == 0);

            Set<SelectionKey> selectedKeys = selector.selectedKeys();

            if (selectedKeys.contains(channelKey))
                client.receive();

            if (selectedKeys.contains(requestChannelKey))
                client.receiveResponse();

            selectedKeys.clear();
        }
    }
}
 
Example 15
Source File: UdpBootstrap.java    From smart-socket with Apache License 2.0 5 votes vote down vote up
/**
 * 开启一个UDP通道
 *
 * @param host 绑定本机地址
 * @param port 指定绑定端口号,为0则随机指定
 */
public UdpChannel<Request> open(String host, int port) throws IOException {
    if (selector == null) {
        synchronized (this) {
            if (selector == null) {
                selector = Selector.open();
            }
        }
    }

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(false);
    if (port > 0) {
        channel.socket().bind(host == null ? new InetSocketAddress(port) : new InetSocketAddress(host, port));
    }

    if (status == Status.STATUS_RUNNING) {
        selector.wakeup();
    }
    SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_READ);
    UdpChannel<Request> udpChannel = new UdpChannel<>(channel, selectionKey, config, bufferPage);
    selectionKey.attach(udpChannel);

    //启动线程服务
    if (status == Status.STATUS_INIT) {
        initThreadServer();
    }
    return udpChannel;
}
 
Example 16
Source File: TestNonBlockingNIO2.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 17
Source File: GelfUDPSender.java    From xian with Apache License 2.0 5 votes vote down vote up
private DatagramChannel initiateChannel() throws IOException {
    DatagramChannel resultingChannel = DatagramChannel.open();
    resultingChannel.socket().bind(new InetSocketAddress(0));
    resultingChannel.connect(new InetSocketAddress(this.host, this.port));
    resultingChannel.configureBlocking(false);

    return resultingChannel;
}
 
Example 18
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testProcessCommand_udp_transmitter() throws IOException {
    System.out.println("UDP transmitter");
    String cmd = "udp-transmitter:localhost:3333:cpu\tmemory\ttcp\n";
    final DatagramChannel channel = DatagramChannelEmul.open();
    channel.configureBlocking(false);
    final InetSocketAddress inetSocketAddress = new InetSocketAddress(
            "localhost", 4444);
    channel.connect(inetSocketAddress);
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), channel, inetSocketAddress);
    instance.addCommandString(cmd);
    instance.processNextCommand();
}
 
Example 19
Source File: Statsd.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private DatagramChannel createDatagramChannel() throws IOException {
	final DatagramChannel channel = DatagramChannel.open();
	// Put this in non-blocking mode so send does not block forever.
	channel.configureBlocking(false);
	// Increase the size of the output buffer so that the size is larger than our buffer size.
	channel.setOption(StandardSocketOptions.SO_SNDBUF, SOCKET_BUFFER_SIZE);
	return channel;
}
 
Example 20
Source File: MarketData.java    From parity with Apache License 2.0 4 votes vote down vote up
static MarketData open(String session, NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup,
        InetSocketAddress requestAddress) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
    channel.connect(multicastGroup);

    MoldUDP64Server transport = new MoldUDP64Server(channel, session);

    DatagramChannel requestChannel = DatagramChannel.open();

    requestChannel.bind(requestAddress);
    requestChannel.configureBlocking(false);

    MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);

    return new MarketData(transport, requestTransport);
}