List of usage examples for java.nio.channels DatagramChannel open
public static DatagramChannel open() throws IOException
From source file:com.googlecode.jmxtrans.model.output.StatsDWriter.java
/** * Uses JmxUtils.getDefaultPoolMap()/*w w w. j a v a 2s . co m*/ * * @throws IOException */ @JsonCreator public StatsDWriter(@JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("host") String host, @JsonProperty("port") Integer port, @JsonProperty("bucketType") String bucketType, @JsonProperty("rootPrefix") String rootPrefix, @JsonProperty(STRING_VALUE_AS_KEY) Boolean stringsValuesAsKey, @JsonProperty(STRING_VALUE_DEFAULT_COUNTER) Long stringValueDefaultCount, @JsonProperty("settings") Map<String, Object> settings) throws IOException { super(typeNames, booleanAsNumber, debugEnabled, settings); log.warn("StatsDWriter is deprecated. Please use StatsDWriterFactory instead."); channel = DatagramChannel.open(); sendBuffer = ByteBuffer.allocate((short) 1500); // bucketType defaults to c == counter this.bucketType = firstNonNull(bucketType, (String) getSettings().get(BUCKET_TYPE), "c"); this.rootPrefix = firstNonNull(rootPrefix, (String) getSettings().get(ROOT_PREFIX), "servers"); // treat string attributes as key this.stringsValuesAsKey = firstNonNull(stringsValuesAsKey, (Boolean) getSettings().get(STRING_VALUE_AS_KEY), false); this.stringValueDefaultCount = firstNonNull(stringValueDefaultCount, (Long) getSettings().get(STRING_VALUE_DEFAULT_COUNTER), 1L); if (host == null) { host = (String) getSettings().get(HOST); } if (port == null) { port = Settings.getIntegerSetting(getSettings(), PORT, null); } checkNotNull(host, "Host cannot be null"); checkNotNull(port, "Port cannot be null"); this.address = new InetSocketAddress(host, port); }
From source file:org.limewire.mojito.io.MessageDispatcherImpl.java
@Override public void bind(SocketAddress address) throws IOException { synchronized (lock) { if (isBound()) { throw new IOException("DatagramChannel is already bound"); }//ww w . jav a 2s. c o m channel = DatagramChannel.open(); channel.configureBlocking(false); selector = Selector.open(); channel.register(selector, SelectionKey.OP_READ); DatagramSocket socket = channel.socket(); socket.setReuseAddress(false); socket.setReceiveBufferSize(RECEIVE_BUFFER_SIZE); socket.setSendBufferSize(SEND_BUFFER_SIZE); socket.bind(address); } }
From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java
private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException { final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>()); Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351 DatagramChannel unicastChannel = null; try {//ww w . j a va 2 s . c o m unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(Collections.singletonList(unicastChannel)); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { new ExternalAddressNatPmpResponse(packet); // should error out if not valid foundGateways.add(sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (InetAddress potentialGateway : potentialGateways) { communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351), outBuf.asReadOnlyBuffer()); } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashSet<>(foundGateways); }
From source file:net.jenet.Host.java
/** * Creates a new <code>Host</code> object. If the incoming/outgoing * bandwidths are not bounded, the host will drop unreliable packets in * order to keep them below the fixed limits. This parameter also influences * the number and size of the reliable packets that may be handled at once. * /*from w ww. j a v a 2 s . c o m*/ * @param address * The to bind this host to (<emph>ie</emph> the address at * which other peers may connect to this one) or * <code>0</code> to get a system-assigned address. * @param maxConnections * The maximum number of peers/connections that this host will be * able to connect to. * @param incomingBandwith * The maximum incoming bandwidth in bytes/second (0 = * unbounded). * @param outgoingBandwith * The maximum outgoing bandwidth in bytes/second (0 = * unbounded). * @throws IOException * if it can not bind the port. * @throws ConfigurationException * if the file enet.properties is not in the path */ public Host(InetSocketAddress address, int maxConnections, int incomingBandwith, int outgoingBandwith) throws IOException, ConfigurationException { super(); communicationChannel = DatagramChannel.open(); communicationChannel.configureBlocking(false); communicationChannel.socket().bind(address); communicationSelector = Selector.open(); communicationChannel.register(communicationSelector, SelectionKey.OP_READ); LOG.debug("Host bound to address: " + address); this.address = (InetSocketAddress) communicationChannel.socket().getLocalSocketAddress(); initHost(maxConnections, incomingBandwith, outgoingBandwith); }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException { final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>()); Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351 DatagramChannel unicastChannel = null; try {//w ww . ja v a 2 s.c o m unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(Collections.singletonList(unicastChannel)); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { foundGateways.add(sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this // should be fine because all we're looking for is a response, not // nessecarily a correct response -- self address being sent is // 0.0.0.0 (IPV4) // // also, we need to pass in MAP because Apple's garbage routers // give back NATPMP responses when you pass in ANNOUNCE outBuf.flip(); for (InetAddress potentialGateway : potentialGateways) { communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351), outBuf.asReadOnlyBuffer()); } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses return new HashSet<>(foundGateways); }
From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java
private static Set<UpnpIgdDevice> scanForDevices(InetSocketAddress multicastSocketAddress, Set<InetAddress> localAddresses, String searchQuery) throws IOException, InterruptedException { final Set<UpnpIgdDevice> ret = Collections.synchronizedSet(new HashSet<UpnpIgdDevice>()); final Map<Channel, InetAddress> bindMap = Collections.synchronizedMap(new HashMap<Channel, InetAddress>()); UdpCommunicatorListener listener = new UdpCommunicatorListener() { @Override//from w ww.j a va2 s . c o m public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { byte[] inPacket = ByteBufferUtils.copyContentsToArray(packet); String inStr; try { inStr = new String(inPacket, 0, inPacket.length, "US-ASCII"); } catch (UnsupportedEncodingException uee) { return; } Matcher matcher; URI url; if ((matcher = LOCATION_PATTERN.matcher(inStr)).find()) { String urlStr = matcher.group(1); try { url = new URI(urlStr); } catch (URISyntaxException urise) { return; } } else { return; } String name = null; if ((matcher = SERVER_PATTERN.matcher(inStr)).find()) { name = matcher.group(1); } InetAddress localAddress = bindMap.get(channel); UpnpIgdDevice device = new UpnpIgdDevice(localAddress, sourceAddress.getAddress(), name, url); ret.add(device); } }; UdpCommunicator comm = null; try { List<DatagramChannel> channels = new ArrayList<>(); for (InetAddress localAddr : localAddresses) { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); channel.bind(new InetSocketAddress(localAddr, 0)); channels.add(channel); bindMap.put(channel, localAddr); } comm = new UdpCommunicator(channels); comm.startAsync().awaitRunning(); comm.addListener(listener); ByteBuffer searchQueryBuffer = ByteBuffer.wrap(searchQuery.getBytes("US-ASCII")).asReadOnlyBuffer(); for (int i = 0; i < 3; i++) { for (DatagramChannel channel : channels) { comm.send(channel, multicastSocketAddress, searchQueryBuffer.asReadOnlyBuffer()); } Thread.sleep(TimeUnit.SECONDS.toMillis(MAX_WAIT + 1)); } return new HashSet<>(ret); } finally { if (comm != null) { try { comm.stopAsync().awaitTerminated(); // this stop should handle closing all the datagram channels } catch (IllegalStateException ise) { // NOPMD // do nothing } } } }
From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java
protected void configureListener(int listenerPort) { // open the listener port try {/*from w ww . j av a 2s . c o m*/ listenerChannel = DatagramChannel.open(); listenerChannel.socket().bind(new InetSocketAddress(listenerPort)); listenerChannel.configureBlocking(false); logger.info("Listening for incoming data on {}", listenerChannel.getLocalAddress()); synchronized (selector) { selector.wakeup(); try { listenerKey = listenerChannel.register(selector, listenerChannel.validOps()); } catch (ClosedChannelException e1) { logger.error("An exception occurred while registering a selector: {}", e1.getMessage()); } } } catch (Exception e2) { logger.error("An exception occurred while creating the Listener Channel on port number {} ({})", listenerPort, e2.getMessage()); } }
From source file:org.opennms.netmgt.syslogd.SyslogdImplementationsIT.java
@Test @Transactional/*from w w w . j a v a 2s. c om*/ public void testDefaultSyslogd() throws Exception { Thread listener = new Thread(m_nio); listener.start(); Thread.sleep(3000); final int eventCount = 100; List<Integer> foos = new ArrayList<Integer>(); for (int i = 0; i < eventCount; i++) { int eventNum = Double.valueOf(Math.random() * 10000).intValue(); foos.add(eventNum); } m_eventCounter.setAnticipated(eventCount); String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1"; SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1")); /* // Test by directly invoking the SyslogConnection task System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, m_config)); } // Test by sending over a java.net socket final DatagramSocket socket = new DatagramSocket(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); socket.send(pkt); } socket.close(); */ // Test by sending over an NIO channel SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT); final DatagramChannel channel = DatagramChannel.open(); final ByteBuffer buffer = ByteBuffer.allocate(SyslogReceiverNioThreadPoolImpl.MAX_PACKET_SIZE); buffer.clear(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo))); buffer.flip(); channel.send(buffer, address); buffer.clear(); } channel.close(); /* */ long mid = System.currentTimeMillis(); System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start)); m_eventCounter.waitForFinish(120000); long end = System.currentTimeMillis(); System.err.println( String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount())); final long total = (end - start); final double eventsPerSecond = (eventCount * 1000.0 / total); System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond)); listener.interrupt(); listener.join(); }
From source file:org.apache.nifi.io.nio.ChannelListener.java
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize) throws IOException { final DatagramChannel dChannel = DatagramChannel.open(); dChannel.configureBlocking(false);/*from w ww . j av a 2 s. co m*/ if (receiveBufferSize > 0) { dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize); final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < receiveBufferSize) { LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to " + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); dChannel.bind(new InetSocketAddress(nicIPAddress, port)); return dChannel; }
From source file:org.openhab.binding.mart.handler.martHandler.java
/** * creates a listener Channel given a port number (listenerPort) * * @param listenerPort//w w w . j av a 2s . co m */ protected void createListenerChannel(int listenerPort) { // opening the listener port which can receive packets on UDP port listenerPort passed to the function try { listenerChannel = DatagramChannel.open(); // used to establish an association between the socket and a local address // once the association is established the socket remains bound until the socket is closed listenerChannel.bind(new InetSocketAddress(listenerPort)); // The Channel must be in non-blocking mode to be used with a Selector listenerChannel.configureBlocking(false); logger.info("Listening for incoming data on {}", listenerChannel.getLocalAddress()); synchronized (selector) { selector.wakeup(); try { // Registers this channel with the given selector, returning a selection key // ".validOps" returns an operation set identifying this channel's supported operations listenerKey = listenerChannel.register(selector, listenerChannel.validOps()); } catch (ClosedChannelException e1) { // TODO: handle exception logger.error("An error occured while registering the selector: {}", e1.getMessage()); } } } catch (IOException e) { // TODO Auto-generated catch block logger.error("An error occured while creating the Listener Channel on port number {} ({})", listenerPort, e.getMessage()); } }