本文整理汇总了Java中io.netty.channel.socket.DatagramChannel类的典型用法代码示例。如果您正苦于以下问题:Java DatagramChannel类的具体用法?Java DatagramChannel怎么用?Java DatagramChannel使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DatagramChannel类属于io.netty.channel.socket包,在下文中一共展示了DatagramChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
public void run() {
try {
Bootstrap boot = new Bootstrap();
boot.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
channel = ch;
ch.pipeline().addLast(new UdpChannelHandlerServer(TF2UdpServer.this));
}
});
boot.bind(port).sync().channel().closeFuture();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例2: init
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
public void init(ChannelPipelineFactory factory) throws Exception
{
id = String.format("%1$020d",
Math.abs(new Random(System.currentTimeMillis()).nextLong()))
.getBytes();
group = new OioEventLoopGroup();
connectionlessBootstrap = new Bootstrap();
connectionlessBootstrap.group(group);
connectionlessBootstrap.option(ChannelOption.SO_BROADCAST, true);
connectionlessBootstrap.handler(factory);
connectionlessBootstrap.channel(OioDatagramChannel.class);
;
datagramChannel = (DatagramChannel) connectionlessBootstrap
.bind(new InetSocketAddress(mcastGroupPort)).sync().channel();
multicastAddress = new InetSocketAddress(mcastGroupIp, mcastGroupPort);
NetworkInterface networkInterface = NetworkInterface
.getByInetAddress(InetAddress.getByName(bindAddress));
// for (Enumeration nifs = NetworkInterface.getNetworkInterfaces();
// nifs.hasMoreElements(); )
datagramChannel.joinGroup(multicastAddress, null);// (NetworkInterface)
// nifs.nextElement());
init = true;
if (debug)
factory.debug();
}
示例3: newHandler
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
@Override
public Mono<? extends NettyContext> newHandler(BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> handler) {
final BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>>
targetHandler =
null == handler ? ChannelOperations.noopHandler() : handler;
return Mono.create(sink -> {
Bootstrap b = options.get();
SocketAddress adr = options.getAddress();
if(adr == null){
sink.error(new NullPointerException("Provided UdpServerOptions do not " +
"define any address to bind to "));
return;
}
b.localAddress(adr);
ContextHandler<DatagramChannel> c = doHandler(targetHandler, sink, adr);
b.handler(c);
c.setFuture(b.bind());
});
}
示例4: newHandler
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
@Override
public Mono<? extends NettyContext> newHandler(BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> handler) {
final BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>>
targetHandler =
null == handler ? ChannelOperations.noopHandler() : handler;
return Mono.create(sink -> {
Bootstrap b = options.get();
SocketAddress adr = options.getAddress();
if(adr == null){
sink.error(new NullPointerException("Provided UdpClientOptions do not " +
"define any address to bind to "));
return;
}
b.remoteAddress(adr);
ContextHandler<DatagramChannel> c = doHandler(targetHandler, sink, adr);
b.handler(c);
c.setFuture(b.connect());
});
}
示例5: activateOptions
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
public void activateOptions() throws InterruptedException {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new Log4jHandler());
b.option(ChannelOption.SO_REUSEADDR, true);
b.option(ChannelOption.IP_MULTICAST_IF, MulticastSettings.getIface());
b.option(ChannelOption.TCP_NODELAY, true);
InetSocketAddress addr = new InetSocketAddress(MulticastSettings.getAddressToBind(), port);
b.localAddress(port).remoteAddress(addr);
ch = (DatagramChannel) b.bind().sync().channel();
ch.joinGroup(multicastAddress, MulticastSettings.getIface()).sync();
}
示例6: run
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
public void run() throws Exception {
// Configure the server.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
public void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new TftpServerHandler());
}
});
b.bind(port).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
示例7: main
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
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();
}
示例8: sendBeacon
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
public void sendBeacon() {
final BeaconMessage msg = beacon.get();
channelLock.readLock().lock();
try {
for (final DatagramChannel channel : channels.values()) {
if (channel.isActive()) {
LOGGER.trace("trying to send on {}", channel);
channel.writeAndFlush(msg).addListener(
new GenericFutureListener<io.netty.util.concurrent.Future<Void>>() {
@Override
public void operationComplete(io.netty.util.concurrent.Future<Void> future)
throws Exception {
LOGGER.trace(future);
}
});
}
}
} finally {
channelLock.readLock().unlock();
}
}
示例9: doJoin
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
private void doJoin(final ChannelFuture bindFuture, final DatagramChannel channel, final NetworkInterface interf,
final InetSocketAddress address, final ChannelPromise promise) {
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
LOGGER.entry(bindFuture, channel, interf, address, promise);
if (bindFuture.isSuccess()) {
LOGGER.debug("joining group {} with {} using {} and promise {}", address, interf, channel, promise);
channel.joinGroup(address, interf, promise);
} else {
promise.setFailure(bindFuture.cause());
}
LOGGER.exit();
}
});
}
示例10: mockChannelHandlerContext
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
/**
* Mock Nettys ChannelHandlerContext with the minimal functions.
*
* @param buf
* The buffer to use for decoding
* @param m2
* The message reference to store the result
* @return The mocked ChannelHandlerContext
*/
@SuppressWarnings("unchecked")
private ChannelHandlerContext mockChannelHandlerContext(final ByteBuf buf,
final AtomicReference<Message2> m2) {
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
ByteBufAllocator alloc = mock(ByteBufAllocator.class);
when(ctx.alloc()).thenReturn(alloc);
when(alloc.ioBuffer()).thenReturn(buf);
DatagramChannel dc = mock(DatagramChannel.class);
when(ctx.channel()).thenReturn(dc);
when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(null);
Attribute<InetSocketAddress> attr = mock(Attribute.class);
when(ctx.attr(any(AttributeKey.class))).thenReturn(attr);
when(ctx.fireChannelRead(any())).then(new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
m2.set((Message2) args[0]);
return null;
}
});
return ctx;
}
示例11: createServer
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
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);
}
}
示例12: channelActive
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
connection.init(ctx.channel(), false);
if (multicastAddress != null) {
((DatagramChannel) ctx.channel()).joinGroup(multicastAddress, networkInterface, null).addListener(future -> {
if (future.isSuccess()) {
LOGGER.info("join multicast group success, channel={}, group={}", ctx.channel(), multicastAddress);
} else {
LOGGER.error("join multicast group error, channel={}, group={}", ctx.channel(), multicastAddress, future.cause());
}
});
}
LOGGER.info("init udp channel={}", ctx.channel());
}
示例13: channelInactive
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
connection.close();
if (multicastAddress != null) {
((DatagramChannel) ctx.channel()).leaveGroup(multicastAddress, networkInterface, null).addListener(future -> {
if (future.isSuccess()) {
LOGGER.info("leave multicast group success, channel={}, group={}", ctx.channel(), multicastAddress);
} else {
LOGGER.error("leave multicast group error, channel={}, group={}", ctx.channel(), multicastAddress, future.cause());
}
});
}
LOGGER.info("disconnect udp channel={}, connection={}", ctx.channel(), connection);
}
示例14: initChannel
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline().addLast("wrapper_encoder", new PocketWrapperEncoder());
ch.pipeline().addLast("packet_decoder", new PocketDecoder());
ch.pipeline().addLast("packet_encoder", new PocketEncoder());
ch.pipeline().addLast("packet_handler", new PocketHandler());
}
示例15: setupUdpChannel
import io.netty.channel.socket.DatagramChannel; //导入依赖的package包/类
protected ChannelHandler setupUdpChannel() {
return new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline().addLast("logger", new LoggingHandler());
ch.pipeline().addLast("packetDecoder", new UdpPacketToByteBuf());
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
ch.pipeline().addLast("putDecoder", new UdpDecoder());
ch.pipeline().addLast(udpWorkerGroup, "putHandler", new TcpPutHandler(dataStore));
}
};
}