io.netty.channel.socket.DatagramChannel Java Examples
The following examples show how to use
io.netty.channel.socket.DatagramChannel.
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: UAS.java From sipstack with MIT License | 6 votes |
public static void main(final String[] args) throws Exception { final UAS uas = new UAS(); final EventLoopGroup udpGroup = new NioEventLoopGroup(); final Bootstrap b = new Bootstrap(); b.group(udpGroup) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(final DatagramChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new SipMessageDatagramDecoder()); pipeline.addLast("encoder", new SipMessageEncoder()); pipeline.addLast("handler", uas); } }); final InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 5060); b.bind(socketAddress).sync().channel().closeFuture().await(); }
Example #2
Source File: VoiceWebsocket.java From kyoko with MIT License | 6 votes |
private void setupUDP(InetSocketAddress addr, int ssrc) { tries.set(0); remoteAddress = addr; logger.info("Attempting UDP discovery, address: {}, ssrc: {}", addr, ssrc); if (udpSocket != null && udpSocket.isConnected()) { udpSocket.close(); } setupNetty(addr, new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { udpSocket = ch; ch.pipeline().addLast("handler", new UDPHolepunchHandler(VoiceWebsocket.this)); holePunch(addr, ssrc); } }).exceptionally(err -> { close(ConnectionStatus.ERROR_UDP_UNABLE_TO_CONNECT); return null; }); }
Example #3
Source File: DefaultLoopKQueue.java From reactor-netty with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> CHANNEL getChannel(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (CHANNEL) new KQueueSocketChannel(); } if (channelClass.equals(ServerSocketChannel.class)) { return (CHANNEL) new KQueueServerSocketChannel(); } if (channelClass.equals(DatagramChannel.class)) { return (CHANNEL) new KQueueDatagramChannel(); } if (channelClass.equals(DomainSocketChannel.class)) { return (CHANNEL) new KQueueDomainSocketChannel(); } if (channelClass.equals(ServerDomainSocketChannel.class)) { return (CHANNEL) new KQueueServerDomainSocketChannel(); } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #4
Source File: DefaultLoopEpoll.java From reactor-netty with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> CHANNEL getChannel(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (CHANNEL) new EpollSocketChannel(); } if (channelClass.equals(ServerSocketChannel.class)) { return (CHANNEL) new EpollServerSocketChannel(); } if (channelClass.equals(DatagramChannel.class)) { return (CHANNEL) new EpollDatagramChannel(); } if (channelClass.equals(DomainSocketChannel.class)) { return (CHANNEL) new EpollDomainSocketChannel(); } if (channelClass.equals(ServerDomainSocketChannel.class)) { return (CHANNEL) new EpollServerDomainSocketChannel(); } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #5
Source File: UdpServerChannel.java From UdpServerSocketChannel with GNU Lesser General Public License v3.0 | 6 votes |
public UdpServerChannel(int ioThreads) { if (ioThreads < 1) { throw new IllegalArgumentException("IO threads cound can't be less than 1"); } boolean epollAvailabe = Epoll.isAvailable(); if (!epollAvailabe) { ioThreads = 1; } group = epollAvailabe ? new EpollEventLoopGroup(ioThreads) : new NioEventLoopGroup(ioThreads); Class<? extends DatagramChannel> channel = epollAvailabe ? EpollDatagramChannel.class : NioDatagramChannel.class; ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() { final ReadRouteChannelHandler ioReadRoute = new ReadRouteChannelHandler(); @Override protected void initChannel(Channel ioChannel) throws Exception { ioChannel.pipeline().addLast(ioReadRoute); } }; while (ioThreads-- > 0) { Bootstrap ioBootstrap = new Bootstrap().group(group).channel(channel).handler(initializer); if (epollAvailabe) { ioBootstrap.option(UnixChannelOption.SO_REUSEPORT, true); } ioBootstraps.add(ioBootstrap); } }
Example #6
Source File: ReliablePacketController.java From riiablo with Apache License 2.0 | 6 votes |
public void sendAck(int channelId, DatagramChannel ch) { if (DEBUG_SEND) Log.debug(TAG, "sendAck"); int ack, ackBits; synchronized (receivedPackets) { ack = receivedPackets.generateAck(); ackBits = receivedPackets.generateAckBits(ack); } ByteBuf packet = ch.alloc().directBuffer(config.packetHeaderSize); int headerSize = Packet.writeAck(packet, channelId, ack, ackBits); if (headerSize < 0) { Log.error(TAG, "failed to write ack"); ReliableEndpoint.stats.NUM_ACKS_INVALID++; return; } channel.onPacketTransmitted(packet); ch.writeAndFlush(packet); }
Example #7
Source File: NettyUnicastService.java From atomix with Apache License 2.0 | 6 votes |
/** * Recursively binds the given bootstrap to the given interfaces. * * @param bootstrap the bootstrap to bind * @param ifaces an iterator of interfaces to which to bind * @param port the port to which to bind * @param future the future to completed once the bootstrap has been bound to all provided interfaces */ private void bind(Bootstrap bootstrap, Iterator<String> ifaces, int port, CompletableFuture<Void> future) { if (ifaces.hasNext()) { String iface = ifaces.next(); bootstrap.bind(iface, port).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { log.info("UDP server listening for connections on {}:{}", iface, port); channel = (DatagramChannel) f.channel(); bind(bootstrap, ifaces, port, future); } else { log.warn("Failed to bind TCP server to port {}:{} due to {}", iface, port, f.cause()); future.completeExceptionally(f.cause()); } }); } else { future.complete(null); } }
Example #8
Source File: DnsAddressResolverGroup.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * @deprecated Override {@link #newNameResolver(EventLoop, ChannelFactory, DnsServerAddressStreamProvider)}. */ @Deprecated protected AddressResolver<InetSocketAddress> newResolver( EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory, DnsServerAddressStreamProvider nameServerProvider) throws Exception { final NameResolver<InetAddress> resolver = new InflightNameResolver<InetAddress>( eventLoop, newNameResolver(eventLoop, channelFactory, nameServerProvider), resolvesInProgress, resolveAllsInProgress); return newAddressResolver(eventLoop, resolver); }
Example #9
Source File: BuilderUtils.java From servicetalk with Apache License 2.0 | 5 votes |
/** * Returns the correct {@link Class} to use with the given {@link EventLoopGroup}. * * @param group the {@link EventLoopGroup} for which the class is needed * @return the class that should be used for bootstrapping */ public static Class<? extends DatagramChannel> datagramChannel(EventLoopGroup group) { if (useEpoll(group)) { return EpollDatagramChannel.class; } else if (useKQueue(group)) { return KQueueDatagramChannel.class; } else { return NioDatagramChannel.class; } }
Example #10
Source File: UdpClientConfig.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override protected Class<? extends Channel> channelType(boolean isDomainSocket) { if (isDomainSocket) { throw new UnsupportedOperationException(); } return DatagramChannel.class; }
Example #11
Source File: NioDatagramChannelTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * 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); } Assert.assertEquals(100, channelGroup.size()); } finally { channelGroup.close().sync(); group.shutdownGracefully().sync(); } }
Example #12
Source File: UdpClientConfig.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override protected ChannelFactory<? extends Channel> connectionFactory(EventLoopGroup elg, boolean isDomainSocket) { if (isDomainSocket) { throw new UnsupportedOperationException(); } if (isPreferNative()) { return () -> loopResources().onChannel(DatagramChannel.class, elg); } else { return () -> new NioDatagramChannel(family()); } }
Example #13
Source File: DisposableChannel.java From reactor-netty with Apache License 2.0 | 5 votes |
/** * When on the server, returns the bind address, * when on the client, returns the remote address. * * @return {@link SocketAddress} */ default SocketAddress address(){ Channel c = channel(); if (c instanceof DatagramChannel) { SocketAddress a = c.remoteAddress(); return a != null ? a : c.localAddress(); } return c.remoteAddress(); }
Example #14
Source File: DefaultLoopEpoll.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> Class<? extends CHANNEL> getChannelClass(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (Class<? extends CHANNEL>) EpollSocketChannel.class; } if (channelClass.equals(ServerSocketChannel.class)) { return (Class<? extends CHANNEL>) EpollServerSocketChannel.class; } if (channelClass.equals(DatagramChannel.class)) { return (Class<? extends CHANNEL>) EpollDatagramChannel.class; } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #15
Source File: DefaultLoopKQueue.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> Class<? extends CHANNEL> getChannelClass(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (Class<? extends CHANNEL>) KQueueSocketChannel.class; } if (channelClass.equals(ServerSocketChannel.class)) { return (Class<? extends CHANNEL>) KQueueServerSocketChannel.class; } if (channelClass.equals(DatagramChannel.class)) { return (Class<? extends CHANNEL>) KQueueDatagramChannel.class; } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #16
Source File: DefaultLoopNIO.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> CHANNEL getChannel(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (CHANNEL) new NioSocketChannel(); } if (channelClass.equals(ServerSocketChannel.class)) { return (CHANNEL) new NioServerSocketChannel(); } if (channelClass.equals(DatagramChannel.class)) { return (CHANNEL) new NioDatagramChannel(); } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #17
Source File: NettyUDPConnector.java From mpush with Apache License 2.0 | 5 votes |
private void createServer(Listener listener, EventLoopGroup eventLoopGroup, ChannelFactory<? extends DatagramChannel> channelFactory) { this.eventLoopGroup = eventLoopGroup; try { Bootstrap b = new Bootstrap(); b.group(eventLoopGroup)//默认是根据机器情况创建Channel,如果机器支持ipv6,则无法使用ipv4的地址加入组播 .channelFactory(channelFactory) .option(ChannelOption.SO_BROADCAST, true) .handler(getChannelHandler()); initOptions(b); //直接绑定端口,不要指定host,不然收不到组播消息 b.bind(port).addListener(future -> { if (future.isSuccess()) { logger.info("udp server start success on:{}", port); if (listener != null) listener.onSuccess(port); } else { logger.error("udp server start failure on:{}", port, future.cause()); if (listener != null) listener.onFailure(future.cause()); } }); } catch (Exception e) { logger.error("udp server start exception", e); if (listener != null) listener.onFailure(e); throw new ServiceException("udp server start exception, port=" + port, e); } }
Example #18
Source File: DefaultLoopNIO.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public <CHANNEL extends Channel> Class<? extends CHANNEL> getChannelClass(Class<CHANNEL> channelClass) { if (channelClass.equals(SocketChannel.class)) { return (Class<? extends CHANNEL>) NioSocketChannel.class; } if (channelClass.equals(ServerSocketChannel.class)) { return (Class<? extends CHANNEL>) NioServerSocketChannel.class; } if (channelClass.equals(DatagramChannel.class)) { return (Class<? extends CHANNEL>) NioDatagramChannel.class; } throw new IllegalArgumentException("Unsupported channel type: " + channelClass.getSimpleName()); }
Example #19
Source File: EventLoopUtil.java From pulsar with Apache License 2.0 | 5 votes |
public static Class<? extends DatagramChannel> getDatagramChannelClass(EventLoopGroup eventLoopGroup) { if (eventLoopGroup instanceof EpollEventLoopGroup) { return EpollDatagramChannel.class; } else { return NioDatagramChannel.class; } }
Example #20
Source File: OioDatagramChannel.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
private void ensureBound() { if (!isActive()) { throw new IllegalStateException( DatagramChannel.class.getName() + " must be bound to join a group."); } }
Example #21
Source File: NioDatagramChannelTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
/** * 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); } Assert.assertEquals(100, channelGroup.size()); } finally { channelGroup.close().sync(); group.shutdownGracefully().sync(); } }
Example #22
Source File: ReliableMessageChannel.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void update(float delta, int channelId, DatagramChannel ch) { packetController.update(delta); time += delta; // see if we can pop messages off of the message queue and put them into the send queue updateQueue(channelId, ch); updateCongestion(delta, channelId, ch); }
Example #23
Source File: ReliableMessageChannel.java From riiablo with Apache License 2.0 | 5 votes |
private void updateQueue(int channelId, DatagramChannel ch) { if (messageQueue.size > 0) { int sendBufferSize = 0; for (int seq = oldestUnacked; ReliableUtils.sequenceLessThan(seq, sequence); seq = (seq + 1) & Packet.USHORT_MAX_VALUE) { if (sendBuffer.exists(seq)) sendBufferSize++; } if (sendBufferSize < sendBuffer.numEntries) { ByteBuf packetData = messageQueue.removeFirst(); sendMessage(channelId, ch, packetData); } } }
Example #24
Source File: ReliableMessageChannel.java From riiablo with Apache License 2.0 | 5 votes |
private void flushPacketBuffer(int channelId, DatagramChannel ch) { if (packetBuffer.readableBytes() > 0) { int outgoingSeq = packetController.sendPacket(channelId, ch, packetBuffer); OutgoingPacketSet outgoingPacket = ackBuffer.insert(outgoingSeq); // store message IDs so we can map packet-level acks to message ID acks outgoingPacket.messageIds.clear(); outgoingPacket.messageIds.addAll(outgoingMessageIds); packetBuffer.clear(); outgoingMessageIds.clear(); } }
Example #25
Source File: TestClient.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { UnicastEndpoint<DatagramPacket> endpoint = new ReliableEndpoint(ch, TestClient.this); TestClient.this.endpoint = endpoint; ch.pipeline() .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint)) ; } }); ChannelFuture f = b.connect("localhost", TestServer.PORT).sync(); sendPacket(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); Gdx.app.exit(); } }
Example #26
Source File: ReliableEndpoint.java From riiablo with Apache License 2.0 | 5 votes |
public ReliableEndpoint(DatagramChannel channel, PacketProcessor packetProcessor) { this.channel = channel; this.packetProcessor = packetProcessor; // for my purposes 3 works, channelId can be up to 255 though channels = new MessageChannel[3]; channels[QoS.Reliable.ordinal()] = new ReliableMessageChannel(this); channels[QoS.Unreliable.ordinal()] = new UnreliableMessageChannel(this); channels[QoS.UnreliableOrdered.ordinal()] = new UnreliableOrderedMessageChannel(this); defaultChannels = new EnumIntMap<>(QoS.class, -1); for (QoS qos : QoS.values()) { defaultChannels.put(qos, qos.ordinal()); } }
Example #27
Source File: TestServer.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { ReliableEndpoint endpoint = new ReliableEndpoint(ch, TestServer.this); TestServer.this.endpoint = endpoint; ch.pipeline() .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint)) ; } }) ; ChannelFuture f = b.bind(PORT).sync(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); Gdx.app.exit(); } }
Example #28
Source File: Client.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { final ClientHandler client = new ClientHandler(); ch.pipeline() .addLast(client) .addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { client.init(ctx); client.init(ctx); client.init(ctx); ctx.pipeline().remove(this); } }) ; } }); ChannelFuture f = b.connect("localhost", Main.PORT); f.channel().closeFuture().sync(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); } finally { group.shutdownGracefully(); } }
Example #29
Source File: Main.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); EventLoopGroup bossGroup = new NioEventLoopGroup(); // EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(bossGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { ch.pipeline() .addLast(new ServerHandler()) ; } }) ; ChannelFuture f = b.bind(PORT).sync(); f.channel().closeFuture().sync(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); } finally { // workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
Example #30
Source File: SimpleSipStack.java From sipstack with MIT License | 5 votes |
private Bootstrap createUDPListeningPoint(final SimpleChannelInboundHandler<SipMessageEvent> handler) { final Bootstrap b = new Bootstrap(); b.group(this.udpGroup) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(final DatagramChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new SipMessageDatagramDecoder()); pipeline.addLast("encoder", new SipMessageEncoder()); pipeline.addLast("handler", handler); } }); return b; }