Search in sources :

Example 6 with DatagramChannel

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

the class DatagramMulticastTest method testMulticast.

public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
    NetworkInterface iface = multicastNetworkInterface();
    assumeTrue(iface != null, "No NetworkInterface found that supports multicast and " + socketInternetProtocalFamily());
    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, iface);
    sb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, iface);
    cb.option(ChannelOption.SO_REUSEADDR, true);
    DatagramChannel sc = (DatagramChannel) sb.bind(newSocketAddress(iface)).sync().channel();
    assertEquals(iface, sc.config().getNetworkInterface());
    assertInterfaceAddress(iface, sc.config().getInterface());
    InetSocketAddress addr = sc.localAddress();
    cb.localAddress(addr.getPort());
    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();
    assertEquals(iface, cc.config().getNetworkInterface());
    assertInterfaceAddress(iface, cc.config().getInterface());
    InetSocketAddress groupAddress = SocketUtils.socketAddress(groupAddress(), addr.getPort());
    cc.joinGroup(groupAddress, iface).sync();
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    assertTrue(mhandler.await());
    // leave the group
    cc.leaveGroup(groupAddress, iface).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();
    cc.config().setLoopbackModeDisabled(false);
    sc.config().setLoopbackModeDisabled(false);
    assertFalse(cc.config().isLoopbackModeDisabled());
    assertFalse(sc.config().isLoopbackModeDisabled());
    cc.config().setLoopbackModeDisabled(true);
    sc.config().setLoopbackModeDisabled(true);
    assertTrue(cc.config().isLoopbackModeDisabled());
    assertTrue(sc.config().isLoopbackModeDisabled());
    sc.close().awaitUninterruptibly();
    cc.close().awaitUninterruptibly();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) 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) NetworkInterface(java.net.NetworkInterface) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 7 with DatagramChannel

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

the class DnsClient method main.

public static void main(String[] args) throws Exception {
    InetSocketAddress addr = new InetSocketAddress(DNS_SERVER_HOST, DNS_SERVER_PORT);
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<DatagramChannel>() {

            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new DatagramDnsQueryEncoder()).addLast(new DatagramDnsResponseDecoder()).addLast(new SimpleChannelInboundHandler<DatagramDnsResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) {
                        try {
                            handleQueryResp(msg);
                        } finally {
                            ctx.close();
                        }
                    }
                });
            }
        });
        final Channel ch = b.bind(0).sync().channel();
        DnsQuery query = new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
        ch.writeAndFlush(query).sync();
        boolean succ = ch.closeFuture().await(10, TimeUnit.SECONDS);
        if (!succ) {
            System.err.println("dns query timeout!");
            ch.close().sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPipeline(io.netty.channel.ChannelPipeline) DatagramDnsQueryEncoder(io.netty.handler.codec.dns.DatagramDnsQueryEncoder) DatagramDnsResponse(io.netty.handler.codec.dns.DatagramDnsResponse) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) Bootstrap(io.netty.bootstrap.Bootstrap) DnsQuery(io.netty.handler.codec.dns.DnsQuery) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) DatagramDnsResponseDecoder(io.netty.handler.codec.dns.DatagramDnsResponseDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion)

Example 8 with DatagramChannel

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

the class NioDatagramChannelTest method testBindMultiple.

/**
 * Test try to reproduce issue #1335
 */
@Test
public void testBindMultiple() throws Exception {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        for (int i = 0; i < 100; i++) {
            Bootstrap udpBootstrap = new Bootstrap();
            udpBootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    // Discard
                    ReferenceCountUtil.release(msg);
                }
            });
            DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
            channelGroup.add(datagramChannel);
        }
        assertEquals(100, channelGroup.size());
    } finally {
        channelGroup.close().sync();
        group.shutdownGracefully().sync();
    }
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(io.netty.channel.socket.DatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 9 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel in project traccar by tananaev.

the class EelinkProtocolDecoder method decodePackage.

protected Position decodePackage(Channel channel, SocketAddress remoteAddress, ByteBuf buf, String uniqueId, DeviceSession deviceSession) throws Exception {
    // header
    buf.skipBytes(2);
    int type = buf.readUnsignedByte();
    buf = buf.readSlice(buf.readUnsignedShort());
    int index = buf.readUnsignedShort();
    if (type != MSG_GPS && type != MSG_DATA) {
        ByteBuf content = Unpooled.buffer();
        if (type == MSG_LOGIN) {
            content.writeInt((int) (System.currentTimeMillis() / 1000));
            // protocol version
            content.writeShort(1);
            // action mask
            content.writeByte(0);
        }
        ByteBuf response = EelinkProtocolEncoder.encodeContent(channel instanceof DatagramChannel, uniqueId, type, index, content);
        content.release();
        if (channel != null) {
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
    }
    if (type == MSG_LOGIN) {
        if (deviceSession == null) {
            getDeviceSession(channel, remoteAddress, ByteBufUtil.hexDump(buf.readSlice(8)).substring(1));
        }
    } else {
        if (deviceSession == null) {
            return null;
        }
        if (type == MSG_GPS || type == MSG_ALARM || type == MSG_STATE || type == MSG_SMS) {
            return decodeOld(deviceSession, buf, type, index);
        } else if (type >= MSG_NORMAL && type <= MSG_OBD_CODE) {
            return decodeNew(deviceSession, buf, type, index);
        } else if (type == MSG_HEARTBEAT && buf.readableBytes() >= 2 || type == MSG_OBD && buf.readableBytes() == 4) {
            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());
            getLastLocation(position, null);
            decodeStatus(position, buf.readUnsignedShort());
            return position;
        } else if (type == MSG_OBD) {
            return decodeObd(deviceSession, buf);
        } else if (type == MSG_DOWNLINK) {
            return decodeResult(deviceSession, buf, index);
        }
    }
    return null;
}
Also used : Position(org.traccar.model.Position) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) NetworkMessage(org.traccar.NetworkMessage)

Example 10 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel in project traccar by tananaev.

the class NetworkMessageHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (ctx.channel() instanceof DatagramChannel) {
        DatagramPacket packet = (DatagramPacket) msg;
        ctx.fireChannelRead(new NetworkMessage(packet.content(), packet.sender()));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buffer = (ByteBuf) msg;
        ctx.fireChannelRead(new NetworkMessage(buffer, ctx.channel().remoteAddress()));
    }
}
Also used : DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(io.netty.channel.socket.DatagramChannel) NetworkMessage(org.traccar.NetworkMessage) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

DatagramChannel (io.netty.channel.socket.DatagramChannel)19 InetSocketAddress (java.net.InetSocketAddress)12 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)8 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 EventLoopGroup (io.netty.channel.EventLoopGroup)6 DatagramPacket (io.netty.channel.socket.DatagramPacket)6 ByteBuf (io.netty.buffer.ByteBuf)5 UnknownHostException (java.net.UnknownHostException)4 NetworkMessage (org.traccar.NetworkMessage)4 List (java.util.List)3 DnsMessage (org.apache.directory.server.dns.messages.DnsMessage)3 QuestionRecord (org.apache.directory.server.dns.messages.QuestionRecord)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 ChannelPipeline (io.netty.channel.ChannelPipeline)2 EventLoop (io.netty.channel.EventLoop)2 FixedRecvByteBufAllocator (io.netty.channel.FixedRecvByteBufAllocator)2 DefaultChannelGroup (io.netty.channel.group.DefaultChannelGroup)2 MessageToMessageDecoder (io.netty.handler.codec.MessageToMessageDecoder)2