Search in sources :

Example 6 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class NioDatagramChannel method filterOutboundMessage.

@Override
protected Object filterOutboundMessage(Object msg) {
    if (msg instanceof DatagramPacket) {
        DatagramPacket p = (DatagramPacket) msg;
        ByteBuf content = p.content();
        if (isSingleDirectBuffer(content)) {
            return p;
        }
        return new DatagramPacket(newDirectBuffer(p, content), p.recipient());
    }
    if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;
        if (isSingleDirectBuffer(buf)) {
            return buf;
        }
        return newDirectBuffer(buf);
    }
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked") AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
        if (e.content() instanceof ByteBuf) {
            ByteBuf content = (ByteBuf) e.content();
            if (isSingleDirectBuffer(content)) {
                return e;
            }
            return new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(newDirectBuffer(e, content), e.recipient());
        }
    }
    throw new UnsupportedOperationException("unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
Also used : DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope) AddressedEnvelope(io.netty.channel.AddressedEnvelope) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope)

Example 7 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class NioDatagramChannel method doReadMessages.

@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();
        }
    }
}
Also used : RecvByteBufAllocator(io.netty.channel.RecvByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(java.nio.channels.DatagramChannel) DatagramChannelConfig(io.netty.channel.socket.DatagramChannelConfig) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer)

Example 8 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class OioDatagramChannel method doReadMessages.

@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannelConfig config = config();
    final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
    ByteBuf data = config.getAllocator().heapBuffer(allocHandle.guess());
    boolean free = true;
    try {
        tmpPacket.setData(data.array(), data.arrayOffset(), data.capacity());
        socket.receive(tmpPacket);
        InetSocketAddress remoteAddr = (InetSocketAddress) tmpPacket.getSocketAddress();
        allocHandle.lastBytesRead(tmpPacket.getLength());
        buf.add(new DatagramPacket(data.writerIndex(allocHandle.lastBytesRead()), localAddress(), remoteAddr));
        free = false;
        return 1;
    } catch (SocketTimeoutException e) {
        // Expected
        return 0;
    } catch (SocketException e) {
        if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
            throw e;
        }
        return -1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}
Also used : RecvByteBufAllocator(io.netty.channel.RecvByteBufAllocator) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannelConfig(io.netty.channel.socket.DatagramChannelConfig) DefaultDatagramChannelConfig(io.netty.channel.socket.DefaultDatagramChannelConfig) ByteBuf(io.netty.buffer.ByteBuf)

Example 9 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DatagramMulticastTest method testMulticast.

public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
    MulticastTestHandler mhandler = new MulticastTestHandler();
    sb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // Nothing will be sent.
        }
    });
    cb.handler(mhandler);
    sb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    sb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    cb.option(ChannelOption.SO_REUSEADDR, true);
    cb.localAddress(addr.getPort());
    Channel sc = sb.bind().sync().channel();
    if (sc instanceof OioDatagramChannel) {
        // skip the test for OIO, as it fails because of
        // No route to host which makes no sense.
        // Maybe a JDK bug ?
        sc.close().awaitUninterruptibly();
        return;
    }
    DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();
    String group = "230.0.0.1";
    InetSocketAddress groupAddress = SocketUtils.socketAddress(group, addr.getPort());
    cc.joinGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    assertTrue(mhandler.await());
    // leave the group
    cc.leaveGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
    // sleep a second to make sure we left the group
    Thread.sleep(1000);
    // we should not receive a message anymore as we left the group before
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    mhandler.await();
    sc.close().awaitUninterruptibly();
    cc.close().awaitUninterruptibly();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) Channel(io.netty.channel.Channel) DatagramChannel(io.netty.channel.socket.DatagramChannel) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramPacket(io.netty.channel.socket.DatagramPacket) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 10 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DatagramUnicastTest method testSimpleSend0.

@SuppressWarnings("deprecation")
private void testSimpleSend0(Bootstrap sb, Bootstrap cb, ByteBuf buf, boolean bindClient, final byte[] bytes, int count) throws Throwable {
    final CountDownLatch latch = new CountDownLatch(count);
    sb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
                    ByteBuf buf = msg.content();
                    assertEquals(bytes.length, buf.readableBytes());
                    for (byte b : bytes) {
                        assertEquals(b, buf.readByte());
                    }
                    latch.countDown();
                }
            });
        }
    });
    cb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception {
        // Nothing will be sent.
        }
    });
    Channel sc = null;
    BindException bindFailureCause = null;
    for (int i = 0; i < 3; i++) {
        try {
            sc = sb.bind().sync().channel();
            break;
        } catch (Exception e) {
            if (e instanceof BindException) {
                logger.warn("Failed to bind to a free port; trying again", e);
                bindFailureCause = (BindException) e;
                refreshLocalAddress(sb);
            } else {
                throw e;
            }
        }
    }
    if (sc == null) {
        throw bindFailureCause;
    }
    Channel cc;
    if (bindClient) {
        cc = cb.bind().sync().channel();
    } else {
        cb.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
        cc = cb.register().sync().channel();
    }
    for (int i = 0; i < count; i++) {
        cc.write(new DatagramPacket(buf.retain().duplicate(), addr));
    }
    // release as we used buf.retain() before
    buf.release();
    cc.flush();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    sc.close().sync();
    cc.close().sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Channel(io.netty.channel.Channel) BindException(java.net.BindException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) BindException(java.net.BindException) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)25 ByteBuf (io.netty.buffer.ByteBuf)17 InetSocketAddress (java.net.InetSocketAddress)13 Test (org.junit.Test)7 Channel (io.netty.channel.Channel)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 DefaultAddressedEnvelope (io.netty.channel.DefaultAddressedEnvelope)3 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)3 SocketException (java.net.SocketException)3 BaseLoadBalancer (com.netflix.loadbalancer.BaseLoadBalancer)2 Server (com.netflix.loadbalancer.Server)2 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)2 AddressedEnvelope (io.netty.channel.AddressedEnvelope)2 RecvByteBufAllocator (io.netty.channel.RecvByteBufAllocator)2 DatagramChannelConfig (io.netty.channel.socket.DatagramChannelConfig)2 ObservableConnection (io.reactivex.netty.channel.ObservableConnection)2 UdpServer (io.reactivex.netty.protocol.udp.server.UdpServer)2 SocketAddress (java.net.SocketAddress)2 GlowServer (net.glowstone.GlowServer)2 Observable (rx.Observable)2