Search in sources :

Example 31 with DatagramChannel

use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.

the class GelfUDPSender method connect.

protected void connect() throws IOException {
    if (isConnected()) {
        return;
    }
    if (channel() == null) {
        setChannel(DatagramChannel.open());
    } else if (!channel().isOpen()) {
        Closer.close(channel());
        setChannel(DatagramChannel.open());
    }
    channel().configureBlocking(false);
    InetSocketAddress inetSocketAddress = new InetSocketAddress(getHost(), getPort());
    try {
        DatagramChannel connect = channel().connect(inetSocketAddress);
        setChannel(connect);
    } catch (SocketException e) {
        reportError(e.getMessage(), e);
    }
}
Also used : SocketException(java.net.SocketException) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel)

Example 32 with DatagramChannel

use of java.nio.channels.DatagramChannel in project pi314.notes by pi314.

the class ToyVpnService method run.

private boolean run(InetSocketAddress server) throws Exception {
    DatagramChannel tunnel = null;
    boolean connected = false;
    try {
        // Create a DatagramChannel as the VPN tunnel.
        tunnel = DatagramChannel.open();
        // Protect the tunnel before connecting to avoid loopback.
        if (!protect(tunnel.socket())) {
            throw new IllegalStateException("Cannot protect the tunnel");
        }
        // Connect to the server.
        tunnel.connect(server);
        // For simplicity, we use the same thread for both reading and
        // writing. Here we put the tunnel into non-blocking mode.
        tunnel.configureBlocking(false);
        // Authenticate and configure the virtual network interface.
        handshake(tunnel);
        // Now we are connected. Set the flag and show the message.
        connected = true;
        mHandler.sendEmptyMessage(R.string.connected);
        // Packets to be sent are queued in this input stream.
        FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
        // Packets received need to be written to this output stream.
        FileOutputStream out = new FileOutputStream(mInterface.getFileDescriptor());
        // Allocate the buffer for a single packet.
        ByteBuffer packet = ByteBuffer.allocate(32767);
        // We use a timer to determine the status of the tunnel. It
        // works on both sides. A positive value means sending, and
        // any other means receiving. We start with receiving.
        int timer = 0;
        // We keep forwarding packets till something goes wrong.
        while (true) {
            // Assume that we did not make any progress in this iteration.
            boolean idle = true;
            // Read the outgoing packet from the input stream.
            int length = in.read(packet.array());
            if (length > 0) {
                // Write the outgoing packet to the tunnel.
                packet.limit(length);
                tunnel.write(packet);
                packet.clear();
                // There might be more outgoing packets.
                idle = false;
                // If we were receiving, switch to sending.
                if (timer < 1) {
                    timer = 1;
                }
            }
            // Read the incoming packet from the tunnel.
            length = tunnel.read(packet);
            if (length > 0) {
                // Ignore control messages, which start with zero.
                if (packet.get(0) != 0) {
                    // Write the incoming packet to the output stream.
                    out.write(packet.array(), 0, length);
                }
                packet.clear();
                // There might be more incoming packets.
                idle = false;
                // If we were sending, switch to receiving.
                if (timer > 0) {
                    timer = 0;
                }
            }
            // fraction of time to avoid busy looping.
            if (idle) {
                Thread.sleep(100);
                // Increase the timer. This is inaccurate but good enough,
                // since everything is operated in non-blocking mode.
                timer += (timer > 0) ? 100 : -100;
                // heartbeat
                if (timer < -15000) {
                    // Send empty control messages.
                    packet.put((byte) 0).limit(1);
                    for (int i = 0; i < 3; ++i) {
                        packet.position(0);
                        tunnel.write(packet);
                    }
                    packet.clear();
                    // Switch to sending.
                    timer = 1;
                }
                // We are sending for a long time but not receiving.
                if (timer > 20000) {
                    throw new IllegalStateException("Timed out");
                }
            }
        }
    } catch (InterruptedException e) {
        throw e;
    } catch (Exception e) {
        Log.e(TAG, "Got " + e.toString());
    } finally {
        try {
            tunnel.close();
        } catch (Exception e) {
        // ignore
        }
    }
    return connected;
}
Also used : FileOutputStream(java.io.FileOutputStream) DatagramChannel(java.nio.channels.DatagramChannel) ByteBuffer(java.nio.ByteBuffer) FileInputStream(java.io.FileInputStream)

Example 33 with DatagramChannel

use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.

the class GelfUDPSender method initiateChannel.

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;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel)

Example 34 with DatagramChannel

use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.

the class GraylogUdpConnPool method initiateChannel.

private DatagramChannel initiateChannel() throws IOException {
    DatagramChannel resultingChannel = DatagramChannel.open();
    resultingChannel.socket().bind(new InetSocketAddress(0));
    resultingChannel.connect(new InetSocketAddress(this.host, port));
    resultingChannel.configureBlocking(false);
    return resultingChannel;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel)

Example 35 with DatagramChannel

use of java.nio.channels.DatagramChannel in project reactor-netty by reactor.

the class UdpServerTests method supportsReceivingDatagrams.

@Test
@Ignore
public void supportsReceivingDatagrams() throws InterruptedException {
    final int port = SocketUtils.findAvailableUdpPort();
    final CountDownLatch latch = new CountDownLatch(4);
    final NettyContext server = UdpServer.create(port).newHandler((in, out) -> {
        in.receive().asByteArray().log().subscribe(bytes -> {
            if (bytes.length == 1024) {
                latch.countDown();
            }
        });
        return Flux.never();
    }).doOnSuccess(v -> {
        try {
            DatagramChannel udp = DatagramChannel.open();
            udp.configureBlocking(true);
            udp.connect(new InetSocketAddress(InetAddress.getLocalHost(), port));
            byte[] data = new byte[1024];
            new Random().nextBytes(data);
            for (int i = 0; i < 4; i++) {
                udp.write(ByteBuffer.wrap(data));
            }
            udp.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }).block(Duration.ofSeconds(30));
    assertThat("latch was counted down", latch.await(10, TimeUnit.SECONDS));
    server.dispose();
}
Also used : ChannelOption(io.netty.channel.ChannelOption) Enumeration(java.util.Enumeration) DatagramChannel(java.nio.channels.DatagramChannel) Random(java.util.Random) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) SocketException(java.net.SocketException) Loggers(reactor.util.Loggers) Duration(java.time.Duration) After(org.junit.After) Logger(reactor.util.Logger) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) Schedulers(reactor.core.scheduler.Schedulers) SocketUtils(reactor.ipc.netty.SocketUtils) LoopResources(reactor.ipc.netty.resources.LoopResources) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Collection(java.util.Collection) NetworkInterface(java.net.NetworkInterface) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Test(org.junit.Test) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) Ignore(org.junit.Ignore) MulticastSocket(java.net.MulticastSocket) NettyContext(reactor.ipc.netty.NettyContext) DatagramPacket(java.net.DatagramPacket) Random(java.util.Random) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) NettyContext(reactor.ipc.netty.NettyContext) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

DatagramChannel (java.nio.channels.DatagramChannel)214 InetSocketAddress (java.net.InetSocketAddress)92 ByteBuffer (java.nio.ByteBuffer)71 IOException (java.io.IOException)58 MembershipKey (java.nio.channels.MembershipKey)22 DatagramSocket (java.net.DatagramSocket)21 SocketAddress (java.net.SocketAddress)21 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 SocketChannel (java.nio.channels.SocketChannel)17 SelectionKey (java.nio.channels.SelectionKey)16 InetAddress (java.net.InetAddress)13 Selector (java.nio.channels.Selector)13 Test (org.junit.Test)11 SocketException (java.net.SocketException)9 ClosedChannelException (java.nio.channels.ClosedChannelException)9 Histogram (org.HdrHistogram.Histogram)8 CancelledKeyException (java.nio.channels.CancelledKeyException)7 DatagramPacket (java.net.DatagramPacket)5 NetworkInterface (java.net.NetworkInterface)5 ArrayList (java.util.ArrayList)5