Java Examples for io.netty.channel.socket.DatagramChannel
The following java examples will help you to understand the usage of io.netty.channel.socket.DatagramChannel. These source code samples are taken from different open source projects.
Example 1
| Project: openflowjava-master File: UdpSimpleClientInitializer.java View source code |
@Override
public void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
SimpleClientHandler simpleClientHandler = new SimpleClientHandler(isOnlineFuture, scenarioHandler);
simpleClientHandler.setScenario(scenarioHandler);
pipeline.addLast("framer", new UdpSimpleClientFramer());
pipeline.addLast("handler", simpleClientHandler);
isOnlineFuture = null;
}Example 2
| Project: netty4.0.27Learn-master File: NioDatagramChannel.java View source code |
private static DatagramChannel newSocket(SelectorProvider provider) { try { /** * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in * {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise. * * See <a href="See https://github.com/netty/netty/issues/2308">#2308</a>. */ return provider.openDatagramChannel(); } catch (IOException e) { throw new ChannelException("Failed to open a socket.", e); } }
Example 3
| Project: usc-master File: EchoServerUdp.java View source code |
@Override
public void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
System.out.println("EchoServerUdp initChannel");
if (enableEncryption) {
p.addLast(new LoggingHandler("EchoServerUdp Handler 3", LogLevel.TRACE));
p.addLast(secureService.getUdpServerHandler(ch));
}
p.addLast(new LoggingHandler("EchoServerUdp Handler 2", LogLevel.TRACE));
p.addLast(new EchoServerUdpHandler());
p.addLast(new LoggingHandler("EchoServerUdp Handler 1", LogLevel.TRACE));
}Example 4
| Project: mediaserver-master File: UdpNetworkManagerTest.java View source code |
@Test
public void testBindChannel() throws InterruptedException {
// given
final String address = "127.0.0.1";
final int port = 60000;
final ChannelHandler handler = mock(ChannelHandler.class);
this.manager = new UdpNetworkManager();
// when - activate manager and bind channel
manager.activate();
final ChannelFuture future = manager.bindDatagramChannel(address, port, handler);
final DatagramChannel channel = (DatagramChannel) future.sync().channel();
// then
assertTrue(manager.isActive());
assertTrue(future.isSuccess());
assertNotNull(channel);
assertTrue(channel.isOpen());
assertTrue(channel.isActive());
assertFalse(channel.isConnected());
assertEquals(new InetSocketAddress(address, port), channel.localAddress());
// when - deactivate manager
manager.deactivate();
Thread.sleep(UdpNetworkManager.SHUTDOWN_TIME * 1000);
// then
assertFalse(manager.isActive());
assertFalse(channel.isOpen());
assertFalse(channel.isActive());
}Example 5
| Project: mpush-master File: NettyUDPConnector.java View source code |
private void createServer(Listener listener, EventLoopGroup eventLoopGroup, ChannelFactory<? extends DatagramChannel> channelFactory) {
this.eventLoopGroup = eventLoopGroup;
try {
Bootstrap b = new Bootstrap();
//默认是根据机器情况创建Channel,如果机器支持ipv6,则无法使用ipv4的地址加入组播
b.group(eventLoopGroup).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 6
| Project: TomP2P-master File: Decoder.java View source code |
public boolean decode(ChannelHandlerContext ctx, final ByteBuf buf, InetSocketAddress recipient, final InetSocketAddress sender) {
LOG.debug("Decoding of TomP2P starts now. Readable: {}.", buf.readableBytes());
try {
final int readerBefore = buf.readerIndex();
// set the sender of this message for handling timeout
final Attribute<InetSocketAddress> attributeInet = ctx.attr(INET_ADDRESS_KEY);
attributeInet.set(sender);
if (!headerDone) {
headerDone = decodeHeader(buf, recipient, sender);
if (headerDone) {
// store the sender as an attribute
final Attribute<PeerAddress> attributePeerAddress = ctx.attr(PEER_ADDRESS_KEY);
attributePeerAddress.set(message.sender());
message.udp(ctx.channel() instanceof DatagramChannel);
if (message.isFireAndForget() && message.isUdp()) {
//TODO: find better place for this
Dispatcher.removeTimeout(ctx);
}
} else {
return false;
}
}
final boolean donePayload = decodePayload(buf);
decodeSignature(buf, readerBefore, donePayload);
// see https://github.com/netty/netty/issues/1976
buf.discardSomeReadBytes();
return donePayload;
} catch (Exception e) {
ctx.fireExceptionCaught(e);
e.printStackTrace();
return true;
}
}Example 7
| Project: MINA-master File: Netty4UdpBenchmarkServer.java View source code |
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.attr(STATE_ATTRIBUTE).set(State.WAIT_FOR_FIRST_BYTE_LENGTH);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket message) throws Exception {
ByteBuf buffer = message.content();
State state = ctx.attr(STATE_ATTRIBUTE).get();
int length = 0;
Attribute<Integer> lengthAttribute = ctx.attr(LENGTH_ATTRIBUTE);
if (lengthAttribute.get() != null) {
length = lengthAttribute.get();
}
while (buffer.readableBytes() > 0) {
switch(state) {
case WAIT_FOR_FIRST_BYTE_LENGTH:
length = (buffer.readByte() & 255) << 24;
state = State.WAIT_FOR_SECOND_BYTE_LENGTH;
break;
case WAIT_FOR_SECOND_BYTE_LENGTH:
length += (buffer.readByte() & 255) << 16;
state = State.WAIT_FOR_THIRD_BYTE_LENGTH;
break;
case WAIT_FOR_THIRD_BYTE_LENGTH:
length += (buffer.readByte() & 255) << 8;
state = State.WAIT_FOR_FOURTH_BYTE_LENGTH;
break;
case WAIT_FOR_FOURTH_BYTE_LENGTH:
length += (buffer.readByte() & 255);
state = State.READING;
if ((length == 0) && (buffer.readableBytes() == 0)) {
ctx.writeAndFlush(new DatagramPacket(ACK.retain(1).resetReaderIndex(), message.sender()));
state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
}
break;
case READING:
int remaining = buffer.readableBytes();
if (length > remaining) {
length -= remaining;
buffer.skipBytes(remaining);
} else {
buffer.skipBytes(length);
ctx.writeAndFlush(new DatagramPacket(ACK.retain(1).resetReaderIndex(), message.sender()));
state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
length = 0;
}
}
}
ctx.attr(STATE_ATTRIBUTE).set(state);
ctx.attr(LENGTH_ATTRIBUTE).set(length);
}
});
}Example 8
| Project: DroidNavi-master File: TeleLogServer.java View source code |
public RESULT start() {
logger.entry();
RESULT result = RESULT.SUCCESS;
try {
// TCP Server
ServerBootstrap server = new ServerBootstrap();
server.channel(NioServerSocketChannel.class).group(m_tcpEventLoop).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
m_pool.add(ch);
ch.pipeline().addFirst(new PacketHandler());
ch.pipeline().addLast(new HandshakeHandler());
}
;
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
m_pool.remove(ctx.channel());
}
}).option(ChannelOption.SO_BACKLOG, 3).childOption(ChannelOption.SO_KEEPALIVE, true);
m_tcpFuture = server.bind(TCP_LISTEN_PORT).sync();
// MultiCast Server
InetSocketAddress remoteAddr = new InetSocketAddress(InetAddress.getByName("224.1.1.1"), MULTI_LIST_PORT);
Bootstrap b = new Bootstrap();
b.group(m_multiEventLoop).option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_TTL, 2).option(ChannelOption.SO_RCVBUF, 1048576).channelFactory(new ChannelFactory<OioDatagramChannel>() {
@Override
public OioDatagramChannel newChannel() {
OioDatagramChannel ch = new OioDatagramChannel();
return ch;
}
});
b.handler(new ChannelInitializer<OioDatagramChannel>() {
@Override
protected void initChannel(OioDatagramChannel ch) throws Exception {
ch.pipeline().addFirst(new PacketHandler());
ch.pipeline().addLast(new MulticastInbound());
}
});
m_multiFuture = b.bind(MULTI_LIST_PORT).sync();
DatagramChannel ch = (DatagramChannel) m_multiFuture.channel();
// Join Group on all active interfaces
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
if (nic.isUp() && !nic.isVirtual()) {
ch.joinGroup(remoteAddr, nic);
}
}
// Set multi in order to relay TCP events
EventOperator.instance().setMultiCast(ch);
logger.info("Servers started.");
} catch (BindException e) {
shutdown();
result = (m_tcpFuture != null && m_tcpFuture.isSuccess()) ? RESULT.MULTI_BIND_EXCEPTION.cause(e) : RESULT.TCP_BIND_EXCEPTION.cause(e);
} catch (Throwable e) {
shutdown();
result = RESULT.OTHER_EXCEPTION.cause(e);
}
logger.exit(result);
return result;
}Example 9
| Project: camel-master File: SingleUDPNettyServerBootstrapFactory.java View source code |
protected void startServerBootstrap() throws Exception {
// create non-shared worker pool
EventLoopGroup wg = configuration.getWorkerGroup();
if (wg == null) {
// create new pool which we should shutdown when stopping as its not shared
workerGroup = new NettyWorkerPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withWorkerCount(configuration.getWorkerCount()).withName("NettyServerTCPWorker").build();
wg = workerGroup;
}
Bootstrap bootstrap = new Bootstrap();
if (configuration.isNativeTransport()) {
bootstrap.group(wg).channel(EpollDatagramChannel.class);
} else {
bootstrap.group(wg).channel(NioDatagramChannel.class);
}
// We cannot set the child option here
bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
// only set this if user has specified
if (configuration.getReceiveBufferSizePredictor() > 0) {
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(configuration.getReceiveBufferSizePredictor()));
}
if (configuration.getBacklog() > 0) {
bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
}
Map<String, Object> options = configuration.getOptions();
if (options != null) {
for (Map.Entry<String, Object> entry : options.entrySet()) {
String value = entry.getValue().toString();
ChannelOption<Object> option = ChannelOption.valueOf(entry.getKey());
//TODO: find a way to add primitive Netty options without having to add them to the Camel registry.
if (EndpointHelper.isReferenceParameter(value)) {
String name = value.substring(1);
Object o = CamelContextHelper.mandatoryLookup(camelContext, name);
bootstrap.option(option, o);
} else {
bootstrap.option(option, value);
}
}
}
LOG.debug("Created Bootstrap {}", bootstrap);
// set the pipeline factory, which creates the pipeline for each newly created channels
bootstrap.handler(pipelineFactory);
InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);
if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
ChannelFuture channelFuture = bootstrap.bind(configuration.getPort()).sync();
channel = channelFuture.channel();
DatagramChannel datagramChannel = (DatagramChannel) channel;
String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] { configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
allChannels.add(datagramChannel);
} else {
LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
ChannelFuture channelFuture = bootstrap.bind(hostAddress).sync();
channel = channelFuture.channel();
allChannels.add(channel);
}
}Example 10
| Project: hawkular-metrics-master File: PTrans.java View source code |
/**
* Starts this PTrans instance. the calling thread will be blocked until another thread calls {@link #stop()}.
*/
public void start() throws InterruptedException {
log.infoStarting();
group = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
URI metricsUrl = configuration.getMetricsUrl();
VertxHawkularOptions metricsOptions = new VertxHawkularOptions().setEnabled(true).setHost(metricsUrl.getHost()).setPort(metricsUrl.getPort()).setMetricsServiceUri(metricsUrl.getPath()).setHttpOptions(new HttpClientOptions().setMaxPoolSize(configuration.getMaxConnections()).setSsl("https".equalsIgnoreCase(metricsUrl.getScheme()))).setTenant(configuration.getTenant()).setSendTenantHeader(configuration.isSendTenant()).setAuthenticationOptions(new AuthenticationOptions().setEnabled(configuration.isAuthEnabled()).setId(configuration.getAuthId()).setSecret(configuration.getAuthSecret())).setHttpHeaders(configuration.getHttpHeaders()).setBatchSize(configuration.getBatchSize()).setMetricsBridgeEnabled(true).setMetricsBridgeAddress(Constants.METRIC_ADDRESS);
vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(metricsOptions));
nettyToVertxHandler = new NettyToVertxHandler(vertx.eventBus());
Set<Service> services = configuration.getServices();
List<ChannelFuture> closeFutures = new ArrayList<>(services.size());
if (services.contains(Service.TCP)) {
ServerBootstrap serverBootstrap = new ServerBootstrap().group(group, workerGroup).channel(NioServerSocketChannel.class).localAddress(configuration.getTcpPort()).childHandler(new TcpChannelInitializer(nettyToVertxHandler));
ChannelFuture tcpBindFuture = serverBootstrap.bind().syncUninterruptibly();
log.infoServerListening("Server", "TCP", tcpBindFuture.channel().localAddress());
closeFutures.add(tcpBindFuture.channel().closeFuture());
}
if (services.contains(Service.UDP)) {
Bootstrap udpBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class).localAddress(configuration.getUdpPort()).handler(new UdpChannelInitializer(nettyToVertxHandler));
ChannelFuture udpBindFuture = udpBootstrap.bind().syncUninterruptibly();
log.infoServerListening("Syslogd", "UDP", udpBindFuture.channel().localAddress());
closeFutures.add(udpBindFuture.channel().closeFuture());
}
if (services.contains(Service.GANGLIA)) {
NetworkInterface mcIf;
try {
String multicastIfOverride = configuration.getMulticastIfOverride();
if (multicastIfOverride == null) {
Inet4Address hostAddr = (Inet4Address) InetAddress.getLocalHost();
mcIf = NetworkInterface.getByInetAddress(hostAddr);
} else {
mcIf = NetworkInterface.getByName(multicastIfOverride);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
InetSocketAddress gangliaSocket = new InetSocketAddress(configuration.getGangliaGroup(), configuration.getGangliaPort());
Bootstrap gangliaBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_IF, mcIf).localAddress(gangliaSocket).handler(new GangliaChannelInitializer(nettyToVertxHandler));
log.tracef("Ganglia bootstrap is %s", gangliaBootstrap);
ChannelFuture gangliaBindFuture = gangliaBootstrap.bind().syncUninterruptibly();
log.infoServerListening("Ganglia", "UDP", gangliaBindFuture.channel().localAddress());
DatagramChannel gangliaChannel = (DatagramChannel) gangliaBindFuture.channel();
gangliaChannel.joinGroup(gangliaSocket, mcIf);
log.trace("Joined the Ganglia group");
closeFutures.add(gangliaChannel.closeFuture());
}
if (services.contains(Service.STATSD)) {
Bootstrap statsdBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class).localAddress(configuration.getStatsDport()).handler(new StatsdChannelInitializer(nettyToVertxHandler));
ChannelFuture statsdBindFuture = statsdBootstrap.bind().syncUninterruptibly();
log.infoServerListening("Statsd", "UDP", statsdBindFuture.channel().localAddress());
closeFutures.add(statsdBindFuture.channel().closeFuture());
}
if (services.contains(Service.GRAPHITE)) {
CountDownLatch latch = new CountDownLatch(1);
vertx.deployVerticle(new GraphiteServer(configuration), handler -> {
log.infoServerListening("Graphite", "TCP", configuration.getGraphitePort());
latch.countDown();
});
latch.await();
}
if (services.contains(Service.COLLECTD)) {
vertx.deployVerticle(new CollectdServer(configuration), handler -> {
log.infoServerListening("Collectd", "UDP", configuration.getCollectdPort());
});
}
log.infoStarted();
closeFutures.forEach(ChannelFuture::syncUninterruptibly);
}Example 11
| Project: pbase-master File: ClusterStatusPublisher.java View source code |
@Override
public void connect(Configuration conf) throws IOException {
String mcAddress = conf.get(HConstants.STATUS_MULTICAST_ADDRESS, HConstants.DEFAULT_STATUS_MULTICAST_ADDRESS);
int port = conf.getInt(HConstants.STATUS_MULTICAST_PORT, HConstants.DEFAULT_STATUS_MULTICAST_PORT);
final InetAddress ina;
try {
ina = InetAddress.getByName(mcAddress);
} catch (UnknownHostException e) {
close();
throw new IOException("Can't connect to " + mcAddress, e);
}
final InetSocketAddress isa = new InetSocketAddress(mcAddress, port);
InternetProtocolFamily family;
InetAddress localAddress;
if (ina instanceof Inet6Address) {
localAddress = Addressing.getIp6Address();
family = InternetProtocolFamily.IPv6;
} else {
localAddress = Addressing.getIp4Address();
family = InternetProtocolFamily.IPv4;
}
NetworkInterface ni = NetworkInterface.getByInetAddress(localAddress);
Bootstrap b = new Bootstrap();
b.group(group).channelFactory(new HBaseDatagramChannelFactory<Channel>(NioDatagramChannel.class, family)).option(ChannelOption.SO_REUSEADDR, true).handler(new ClusterStatusEncoder(isa));
try {
channel = (DatagramChannel) b.bind(new InetSocketAddress(0)).sync().channel();
channel.joinGroup(ina, ni, null, channel.newPromise()).sync();
channel.connect(isa).sync();
} catch (InterruptedException e) {
close();
throw ExceptionUtil.asInterrupt(e);
}
}Example 12
| Project: vert.x-master File: DnsResolverProvider.java View source code |
@Override
protected NameResolver<InetAddress> newNameResolver(EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory, DnsServerAddresses nameServerAddresses) throws Exception {
DnsNameResolverBuilder builder = new DnsNameResolverBuilder((EventLoop) executor);
builder.hostsFileEntriesResolver( inetHost -> {
InetAddress addr = entries.get(inetHost);
if (addr == null) {
addr = entries.get(inetHost.toLowerCase(Locale.ENGLISH));
}
return addr;
});
builder.channelType(NioDatagramChannel.class);
builder.nameServerAddresses(nameServerAddresses);
builder.optResourceEnabled(options.isOptResourceEnabled());
builder.ttl(options.getCacheMinTimeToLive(), options.getCacheMaxTimeToLive());
builder.negativeTtl(options.getCacheNegativeTimeToLive());
builder.queryTimeoutMillis(options.getQueryTimeout());
builder.maxQueriesPerResolve(options.getMaxQueries());
builder.recursionDesired(options.getRdFlag());
if (options.getSearchDomains() != null) {
builder.searchDomains(options.getSearchDomains());
int ndots = options.getNdots();
if (ndots == -1) {
ndots = AddressResolver.DEFAULT_NDOTS_RESOLV_OPTION;
}
builder.ndots(ndots);
}
return builder.build();
}Example 13
| Project: tomp2p_5-master File: TomP2PDecoder.java View source code |
public boolean decode0(ChannelHandlerContext ctx, final ByteBuf buf, InetSocketAddress recipient, final InetSocketAddress sender) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
// set the sender of this message for handling timeout
final Attribute<InetSocketAddress> attributeInet = ctx.attr(INET_ADDRESS_KEY);
attributeInet.set(sender);
// we don't have the header yet, we need the full header first
if (message == null) {
if (buf.readableBytes() < MessageHeaderCodec.HEADER_SIZE) {
// wait for more data
return false;
}
message = MessageHeaderCodec.decodeHeader(buf, recipient, sender);
// store the sender as an attribute
final Attribute<PeerAddress> attributePeerAddress = ctx.attr(PEER_ADDRESS_KEY);
attributePeerAddress.set(message.getSender());
// we have set the content types already
message.presetContentTypes(true);
message.udp(ctx.channel() instanceof DatagramChannel);
for (Content content : message.getContentTypes()) {
if (content == Content.EMPTY) {
break;
}
if (content == Content.PUBLIC_KEY_SIGNATURE) {
message.setHintSign();
}
contentTypes.offer(content);
}
// in the future
if (message.isKeepAlive()) {
if (ctx.channel().pipeline().names().contains("timeout-server0")) {
ctx.channel().pipeline().remove("timeout-server0");
}
if (ctx.channel().pipeline().names().contains("timeout-server1")) {
ctx.channel().pipeline().remove("timeout-server1");
}
}
LOG.debug("parsed message {}", message);
}
LOG.debug("about to pass message {} to {}", message, message.senderSocket());
if (!message.hasContent()) {
return true;
}
// payload comes here
int size;
while (contentTypes.size() > 0) {
Content content = contentTypes.peek();
switch(content) {
case INTEGER:
if (buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
return false;
}
message.setInteger(buf.readInt());
lastContent = contentTypes.poll();
break;
case LONG:
if (buf.readableBytes() < Utils.LONG_BYTE_SIZE) {
return false;
}
message.setLong(buf.readLong());
lastContent = contentTypes.poll();
break;
case KEY:
if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE) {
return false;
}
byte[] me = new byte[Number160.BYTE_ARRAY_SIZE];
buf.readBytes(me);
message.setKey(new Number160(me));
lastContent = contentTypes.poll();
break;
case BLOOM_FILTER:
if (buf.readableBytes() < Utils.SHORT_BYTE_SIZE) {
return false;
}
size = buf.getUnsignedShort(buf.readerIndex());
if (buf.readableBytes() < size) {
return false;
}
message.setBloomFilter(new SimpleBloomFilter<Number160>(buf));
lastContent = contentTypes.poll();
break;
case SET_NEIGHBORS:
if (neighborSize == -1 && buf.readableBytes() < Utils.BYTE_SIZE) {
return false;
}
if (neighborSize == -1) {
neighborSize = buf.readUnsignedByte();
}
if (neighborSet == null) {
neighborSet = new NeighborSet(-1, new ArrayList<PeerAddress>(neighborSize));
}
for (int i = neighborSet.size(); i < neighborSize; i++) {
int header = buf.getUnsignedShort(buf.readerIndex());
size = PeerAddress.size(header);
if (buf.readableBytes() < size) {
return false;
}
PeerAddress pa = new PeerAddress(buf);
neighborSet.add(pa);
}
message.setNeighborsSet(neighborSet);
lastContent = contentTypes.poll();
neighborSize = -1;
neighborSet = null;
break;
case SET_KEY480:
if (keysSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
return false;
}
if (keysSize == -1) {
keysSize = buf.readInt();
}
if (keys == null) {
keys = new Keys(new ArrayList<Number480>(keysSize));
}
for (int i = keys.size(); i < keysSize; i++) {
if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE) {
return false;
}
byte[] me2 = new byte[Number160.BYTE_ARRAY_SIZE];
buf.readBytes(me2);
Number160 locationKey = new Number160(me2);
buf.readBytes(me2);
Number160 domainKey = new Number160(me2);
buf.readBytes(me2);
Number160 contentKey = new Number160(me2);
keys.add(new Number480(locationKey, domainKey, contentKey));
}
message.setKeys(keys);
lastContent = contentTypes.poll();
keysSize = -1;
keys = null;
break;
case MAP_KEY480_DATA:
if (mapsSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
return false;
}
if (mapsSize == -1) {
mapsSize = buf.readInt();
}
if (dataMap == null) {
dataMap = new DataMap(new HashMap<Number480, Data>(2 * mapsSize));
}
if (data != null) {
if (!data.decodeBuffer(buf)) {
return false;
}
if (!data.decodeDone(buf)) {
return false;
}
data = null;
}
for (int i = dataMap.size(); i < mapsSize; i++) {
if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE) {
return false;
}
byte[] me3 = new byte[Number160.BYTE_ARRAY_SIZE];
buf.readBytes(me3);
Number160 locationKey = new Number160(me3);
buf.readBytes(me3);
Number160 domainKey = new Number160(me3);
buf.readBytes(me3);
Number160 contentKey = new Number160(me3);
data = Data.decodeHeader(buf);
if (data == null) {
return false;
}
dataMap.dataMap().put(new Number480(locationKey, domainKey, contentKey), data);
if (message.isSign()) {
data.publicKey(message.publicKeyReference());
}
if (!data.decodeBuffer(buf)) {
return false;
}
if (!data.decodeDone(buf)) {
return false;
}
data = null;
}
message.setDataMap(dataMap);
lastContent = contentTypes.poll();
mapsSize = -1;
dataMap = null;
break;
case MAP_KEY480_KEY:
if (keysMapSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
return false;
}
if (keysMapSize == -1) {
keysMapSize = buf.readInt();
}
if (keysMap == null) {
keysMap = new KeysMap(new HashMap<Number480, Number160>(2 * keysMapSize));
}
for (int i = keysMap.size(); i < keysMapSize; i++) {
if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE) {
return false;
}
byte[] me3 = new byte[Number160.BYTE_ARRAY_SIZE];
buf.readBytes(me3);
Number160 locationKey = new Number160(me3);
buf.readBytes(me3);
Number160 domainKey = new Number160(me3);
buf.readBytes(me3);
Number160 contentKey = new Number160(me3);
buf.readBytes(me3);
Number160 valueKey = new Number160(me3);
keysMap.put(new Number480(locationKey, domainKey, contentKey), valueKey);
}
message.setKeysMap(keysMap);
lastContent = contentTypes.poll();
keysMapSize = -1;
keysMap = null;
break;
case BYTE_BUFFER:
if (bufferSize == -1 && buf.readableBytes() < Utils.INTEGER_BYTE_SIZE) {
return false;
}
if (bufferSize == -1) {
bufferSize = buf.readInt();
}
if (buffer == null) {
ByteBuf tmp = Unpooled.compositeBuffer();
buffer = new Buffer(tmp, bufferSize);
}
int already = buffer.alreadyRead();
int readable = buf.readableBytes();
int remaining = bufferSize - already;
int toread = Math.min(remaining, readable);
//Unpooled.copiedBuffer(buf.duplicate().writerIndex(writerIndex))
buffer.addComponent(buf.slice(buf.readerIndex(), toread));
// slice and addComponent do not modifie the reader or the writer, thus we need to do this on our own
buf.skipBytes(toread);
// increase writer index
if (buffer.incRead(toread) != bufferSize) {
LOG.debug("we are still looking for data, indicate that we are not finished yet, " + "read = {}, size = {}", buffer.alreadyRead(), bufferSize);
return false;
}
message.setBuffer(buffer);
lastContent = contentTypes.poll();
bufferSize = -1;
buffer = null;
break;
case SET_TRACKER_DATA:
if (trackerDataSize == -1 && buf.readableBytes() < Utils.BYTE_SIZE) {
return false;
}
if (trackerDataSize == -1) {
trackerDataSize = buf.readUnsignedByte();
}
if (trackerData == null) {
trackerData = new TrackerData(new HashMap<PeerAddress, Data>(2 * trackerDataSize), message.getSender());
}
if (currentTrackerData != null) {
if (!currentTrackerData.decodeBuffer(buf)) {
return false;
}
if (!currentTrackerData.decodeDone(buf)) {
return false;
}
currentTrackerData = null;
}
for (int i = trackerData.size(); i < trackerDataSize; i++) {
if (buf.readableBytes() < Utils.BYTE_SIZE) {
return false;
}
int header = buf.getUnsignedShort(buf.readerIndex());
size = PeerAddress.size(header);
if (buf.readableBytes() < size) {
return false;
}
PeerAddress pa = new PeerAddress(buf);
currentTrackerData = Data.decodeHeader(buf);
if (currentTrackerData == null) {
return false;
}
trackerData.map().put(pa, currentTrackerData);
if (message.isSign()) {
currentTrackerData.publicKey(message.publicKeyReference());
}
if (!currentTrackerData.decodeBuffer(buf)) {
return false;
}
if (!currentTrackerData.decodeDone(buf)) {
return false;
}
currentTrackerData = null;
}
message.setTrackerData(trackerData);
lastContent = contentTypes.poll();
trackerDataSize = -1;
trackerData = null;
break;
case PUBLIC_KEY_SIGNATURE:
if (buf.readableBytes() < 2) {
return false;
}
int len = buf.getUnsignedShort(buf.readerIndex());
if (buf.readableBytes() + Utils.SHORT_BYTE_SIZE < len) {
return false;
}
me = new byte[len];
buf.skipBytes(2);
buf.readBytes(me);
Signature signature = signatureFactory.signatureInstance();
PublicKey receivedPublicKey = signatureFactory.decodePublicKey(me);
signature.initVerify(receivedPublicKey);
message.signatureForVerification(signature, receivedPublicKey);
lastContent = contentTypes.poll();
break;
default:
case EMPTY:
break;
}
}
if (message.isSign()) {
if (buf.readableBytes() < Number160.BYTE_ARRAY_SIZE + Number160.BYTE_ARRAY_SIZE) {
return false;
}
byte[] me = new byte[Number160.BYTE_ARRAY_SIZE];
buf.readBytes(me);
Number160 number1 = new Number160(me);
buf.readBytes(me);
Number160 number2 = new Number160(me);
SHA1Signature signatureEncode = new SHA1Signature(number1, number2);
message.receivedSignature(signatureEncode);
}
return true;
}Example 14
| Project: c5-replicator-master File: BeaconService.java View source code |
@Override
protected void doStart() {
eventLoopGroup.next().execute(() -> {
bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true).handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("protobufDecoder", new UdpProtostuffDecoder<>(Availability.getSchema(), false));
p.addLast("protobufEncoder", new UdpProtostuffEncoder<>(Availability.getSchema(), false));
p.addLast("beaconMessageHandler", new BeaconMessageHandler());
}
});
// Wait, this is why we are in a new executor...
//noinspection RedundantCast
bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
broadcastChannel = future.channel();
} else {
LOG.error("Unable to bind! ", future.cause());
notifyFailed(future.cause());
}
});
try {
localIPs = getLocalIPs();
} catch (SocketException e) {
LOG.error("SocketException:", e);
notifyFailed(e);
return;
}
fiber = fiberSupplier.getNewFiber(this::notifyFailed);
fiber.start();
// Schedule fiber tasks and subscriptions.
incomingMessages.subscribe(fiber, this::processWireMessage);
nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest);
moduleInformationProvider.moduleChangeChannel().subscribe(fiber, this::updateCurrentModulePorts);
if (localIPs.isEmpty()) {
LOG.warn("Found no IP addresses to broadcast to other nodes; as a result, only sending to loopback");
}
fiber.scheduleAtFixedRate(this::sendBeacon, BEACON_SERVICE_INITIAL_BROADCAST_DELAY_MILLISECONDS, BEACON_SERVICE_BROADCAST_PERIOD_MILLISECONDS, TimeUnit.MILLISECONDS);
C5Futures.addCallback(moduleInformationProvider.getOnlineModules(), (ImmutableMap<ModuleType, Integer> onlineModuleToPortMap) -> {
updateCurrentModulePorts(onlineModuleToPortMap);
notifyStarted();
}, this::notifyFailed, fiber);
});
}Example 15
| Project: kompics-master File: NettyNetwork.java View source code |
private boolean bindUdpPort(final InetAddress addr, final int port) {
EventLoopGroup group = new NioEventLoopGroup();
bootstrapUDP = new Bootstrap();
bootstrapUDP.group(group).channel(NioDatagramChannel.class).handler(new DatagramHandler(this, Transport.UDP));
bootstrapUDP.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1500, 1500, RECV_BUFFER_SIZE));
bootstrapUDP.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);
bootstrapUDP.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
// bootstrap.setOption("trafficClass", trafficClass);
// bootstrap.setOption("soTimeout", soTimeout);
// bootstrap.setOption("broadcast", broadcast);
bootstrapUDP.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
bootstrapUDP.option(ChannelOption.SO_REUSEADDR, true);
try {
InetSocketAddress iAddr = new InetSocketAddress(addr, port);
udpChannel = (DatagramChannel) bootstrapUDP.bind(iAddr).sync().channel();
//addLocalSocket(iAddr, c);
LOG.info("Successfully bound to ip:port {}:{}", addr, port);
} catch (InterruptedException e) {
LOG.error("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
return false;
}
return true;
}Example 16
| Project: KitchenSync-core-master File: Bootstrapper.java View source code |
/** * Inits the multicast bootstrap for the specified address.<br> * <br> * * The channel initializer allows the many Netty handlers to be specified as * required for the bootstrap ie. one for SSL communication, one for message * encryption/decryption etc etc. Refer to the <a * href="http://netty.io">Netty</a> documentation for more information. * * @param <CHANNEL> * the generic type * @param initializer * the initializer * @param multicast * the multicast * @param networkInterface * the network interface * @param clazz * the clazz */ public <CHANNEL extends DatagramChannel> void initMulticastBootstrap(ChannelInitializer<DatagramChannel> initializer, InetSocketAddress multicast, NetworkInterface networkInterface, Class<? extends CHANNEL> clazz) { String key = createMulticastKey(multicast); if (containsMulticastBootstrap(key)) { log.warn("Multicast bootstrap for {} already initialized", multicast); return; } log.debug("Initializing multicast bootstrap for {} using network interface {}", multicast, networkInterface); Bootstrap b = multicastBootstrap(initializer, multicast, networkInterface, clazz); multicastBootstraps.put(key, b); }
Example 17
| Project: netty-master File: DnsNameResolverTest.java View source code |
private static void testRecursiveResolveCache(boolean cache) throws Exception {
final String hostname = "some.record.netty.io";
final String hostname2 = "some2.record.netty.io";
final TestDnsServer dnsServerAuthority = new TestDnsServer(new HashSet<String>(Arrays.asList(hostname, hostname2)));
dnsServerAuthority.start();
TestDnsServer dnsServer = new RedirectingTestDnsServer(hostname, dnsServerAuthority.localAddress().getAddress().getHostAddress());
dnsServer.start();
TestDnsCache nsCache = new TestDnsCache(cache ? new DefaultDnsCache() : NoopDnsCache.INSTANCE);
TestRecursiveCacheDnsQueryLifecycleObserverFactory lifecycleObserverFactory = new TestRecursiveCacheDnsQueryLifecycleObserverFactory();
EventLoopGroup group = new NioEventLoopGroup(1);
DnsNameResolver resolver = new DnsNameResolver(group.next(), new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), NoopDnsCache.INSTANCE, nsCache, lifecycleObserverFactory, 3000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(dnsServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {
@Override
int dnsRedirectPort(InetAddress server) {
return server.equals(dnsServerAuthority.localAddress().getAddress()) ? dnsServerAuthority.localAddress().getPort() : DNS_PORT;
}
};
// Java7 will strip of the "." so we need to adjust the expected dnsname. Both are valid in terms of the RFC
// so its ok.
String expectedDnsName = PlatformDependent.javaVersion() == 7 ? "dns4.some.record.netty.io" : "dns4.some.record.netty.io.";
try {
resolver.resolveAll(hostname).syncUninterruptibly();
TestDnsQueryLifecycleObserver observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(4, observer.events.size());
QueryWrittenEvent writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(dnsServer.localAddress(), writtenEvent1.dnsServerAddress);
QueryRedirectedEvent redirectedEvent = (QueryRedirectedEvent) observer.events.poll();
assertEquals(expectedDnsName, redirectedEvent.nameServers.get(0).getHostName());
assertEquals(dnsServerAuthority.localAddress(), redirectedEvent.nameServers.get(0));
QueryWrittenEvent writtenEvent2 = (QueryWrittenEvent) observer.events.poll();
assertEquals(dnsServerAuthority.localAddress(), writtenEvent2.dnsServerAddress);
QuerySucceededEvent succeededEvent = (QuerySucceededEvent) observer.events.poll();
if (cache) {
assertNull(nsCache.cache.get("io.", null));
assertNull(nsCache.cache.get("netty.io.", null));
List<DnsCacheEntry> entries = nsCache.cache.get("record.netty.io.", null);
assertEquals(1, entries.size());
assertNull(nsCache.cache.get(hostname, null));
// Test again via cache.
resolver.resolveAll(hostname).syncUninterruptibly();
observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(2, observer.events.size());
writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(expectedDnsName, writtenEvent1.dnsServerAddress.getHostName());
assertEquals(dnsServerAuthority.localAddress(), writtenEvent1.dnsServerAddress);
succeededEvent = (QuerySucceededEvent) observer.events.poll();
resolver.resolveAll(hostname2).syncUninterruptibly();
observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(2, observer.events.size());
writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(expectedDnsName, writtenEvent1.dnsServerAddress.getHostName());
assertEquals(dnsServerAuthority.localAddress(), writtenEvent1.dnsServerAddress);
succeededEvent = (QuerySucceededEvent) observer.events.poll();
// Check that it only queried the cache for record.netty.io.
assertNull(nsCache.cacheHits.get("io."));
assertNull(nsCache.cacheHits.get("netty.io."));
assertNotNull(nsCache.cacheHits.get("record.netty.io."));
assertNull(nsCache.cacheHits.get("some.record.netty.io."));
}
} finally {
resolver.close();
group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
dnsServer.stop();
dnsServerAuthority.stop();
}
}Example 18
| Project: tftp4j-master File: TftpChannelType.java View source code |
@Override
public Class<? extends DatagramChannel> getChannelType() {
return NioDatagramChannel.class;
}Example 19
| Project: javardices-master File: VoidNettyContext.java View source code |
@Override
public Class<? extends DatagramChannel> getDatagramChannelClass() {
return _datagramChannelClass;
}Example 20
| Project: snotel-master File: MetronClientBuilder.java View source code |
public MetronClientBuilder eventLoopGroup(EventLoopGroup eventLoopGroup, Class<? extends DatagramChannel> channelClass) {
this.eventLoopGroup = eventLoopGroup;
this.channelClass = channelClass;
return this;
}Example 21
| Project: armeria-master File: NonDecoratingClientFactory.java View source code |
private static Class<? extends DatagramChannel> datagramChannelType(EventLoopGroup eventLoopGroup) {
if (eventLoopGroup instanceof NioEventLoopGroup) {
return NioDatagramChannel.class;
}
if (eventLoopGroup instanceof EpollEventLoopGroup) {
return EpollDatagramChannel.class;
}
throw unsupportedEventLoopType(eventLoopGroup);
}