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(); }
public void close() { datagramChannel.close(); try { group.shutdownGracefully().sync(); } catch (InterruptedException e) { e.printStackTrace(); } }
public void send(ByteBuf msg) throws Exception { byte[] arr = msg.array(); byte[] buf = new byte[arr.length + id.length]; System.arraycopy(id, 0, buf, 0, id.length); System.arraycopy(arr, 0, buf, id.length, arr.length); ByteBuf bbuf = Unpooled.wrappedBuffer(buf); if (debug && logger != null) logger.info("discovery send " + new String(bbuf.array())); datagramChannel.writeAndFlush(new DatagramPacket(bbuf, multicastAddress)).sync(); // datagramChannel.writeAndFlush(buf, multicastAddress); }