List of usage examples for java.nio.channels DatagramChannel configureBlocking
public final SelectableChannel configureBlocking(boolean block) throws IOException
From source file:DaytimeServer.java
public static void main(String args[]) { try { // Handle startup exceptions at the end of this block // Get an encoder for converting strings to bytes CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); // Allow an alternative port for testing with non-root accounts int port = 13; // RFC867 specifies this port. if (args.length > 0) port = Integer.parseInt(args[0]); // The port we'll listen on SocketAddress localport = new InetSocketAddress(port); // Create and bind a tcp channel to listen for connections on. ServerSocketChannel tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localport); // Also create and bind a DatagramChannel to listen on. DatagramChannel udpserver = DatagramChannel.open(); udpserver.socket().bind(localport); // Specify non-blocking mode for both channels, since our // Selector object will be doing the blocking for us. tcpserver.configureBlocking(false); udpserver.configureBlocking(false); // The Selector object is what allows us to block while waiting // for activity on either of the two channels. Selector selector = Selector.open(); // Register the channels with the selector, and specify what // conditions (a connection ready to accept, a datagram ready // to read) we'd like the Selector to wake up for. // These methods return SelectionKey objects, which we don't // need to retain in this example. tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); // This is an empty byte buffer to receive emtpy datagrams with. // If a datagram overflows the receive buffer size, the extra bytes // are automatically discarded, so we don't have to worry about // buffer overflow attacks here. ByteBuffer receiveBuffer = ByteBuffer.allocate(0); // Now loop forever, processing client connections for (;;) { try { // Handle per-connection problems below // Wait for a client to connect selector.select();//w w w . j a v a 2 s. co m // If we get here, a client has probably connected, so // put our response into a ByteBuffer. String date = new java.util.Date().toString() + "\r\n"; ByteBuffer response = encoder.encode(CharBuffer.wrap(date)); // Get the SelectionKey objects for the channels that have // activity on them. These are the keys returned by the // register() methods above. They are returned in a // java.util.Set. Set keys = selector.selectedKeys(); // Iterate through the Set of keys. for (Iterator i = keys.iterator(); i.hasNext();) { // Get a key from the set, and remove it from the set SelectionKey key = (SelectionKey) i.next(); i.remove(); // Get the channel associated with the key Channel c = (Channel) key.channel(); // Now test the key and the channel to find out // whether something happend on the TCP or UDP channel if (key.isAcceptable() && c == tcpserver) { // A client has attempted to connect via TCP. // Accept the connection now. SocketChannel client = tcpserver.accept(); // If we accepted the connection successfully, // the send our respone back to the client. if (client != null) { client.write(response); // send respone client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { // A UDP datagram is waiting. Receive it now, // noting the address it was sent from. SocketAddress clientAddress = udpserver.receive(receiveBuffer); // If we got the datagram successfully, send // the date and time in a response packet. if (clientAddress != null) udpserver.send(response, clientAddress); } } } catch (java.io.IOException e) { // This is a (hopefully transient) problem with a single // connection: we log the error, but continue running. // We use our classname for the logger so that a sysadmin // can configure logging for this server independently // of other programs. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.WARNING, "IOException in DaytimeServer", e); } catch (Throwable t) { // If anything else goes wrong (out of memory, for example) // then log the problem and exit. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.SEVERE, "FATAL error in DaytimeServer", t); System.exit(1); } } } catch (Exception e) { // This is a startup error: there is no need to log it; // just print a message and exit System.err.println(e); System.exit(1); } }
From source file:gridool.util.net.PoolableSocketChannelFactory.java
private static DatagramChannel createDatagramChannel(final SocketAddress sockAddr, final boolean blocking) { final DatagramChannel ch; try {//w w w . j a va2 s. co m ch = DatagramChannel.open(); ch.configureBlocking(blocking); } catch (IOException e) { LOG.error("Failed to open DatagramChannel.", e); throw new IllegalStateException(e); } try { ch.socket().setBroadcast(false); } catch (SocketException e) { LOG.error("Failed to configure socket.", e); throw new IllegalStateException(e); } try { ch.connect(sockAddr); } catch (IOException e) { LOG.error("Failed to connect socket: " + sockAddr, e); throw new IllegalStateException(e); } return ch; }
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 {//from w w w. ja v a 2s . co 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: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 {/*from w w w. 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.natpmp.NatPmpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {/*from www . j a v a 2 s .c o m*/ for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); 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 InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {/*w w w.j ava 2 s. c om*/ for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go if (packet.remaining() < 4 || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) { return; } InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, bindMap.get(channel)); outBuf.flip(); communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
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/* w w w .j av a2 s .com*/ 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:net.ymate.platform.serv.nio.datagram.NioUdpServer.java
public synchronized void start() throws IOException { if (!__isStarted) { __isStarted = true;// w ww.ja v a2 s . c o m __eventGroup = new NioEventGroup<NioUdpListener>(__serverCfg, __listener, __codec) { @Override protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException { DatagramChannel _channel = DatagramChannel.open(); _channel.configureBlocking(false); _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort())); return _channel; } @Override protected String __doBuildProcessorName() { return StringUtils.capitalize(name()).concat("UdpServer-NioEventProcessor-"); } @Override protected void __doInitProcessors() throws IOException { __processors = new NioEventProcessor[__selectorCount]; for (int _idx = 0; _idx < __selectorCount; _idx++) { __processors[_idx] = new NioEventProcessor<NioUdpListener>(this, __doBuildProcessorName() + _idx) { @Override protected void __doExceptionEvent(SelectionKey key, final Throwable e) { final INioSession _session = (INioSession) key.attachment(); if (_session != null) { __eventGroup.executorService().submit(new Runnable() { public void run() { try { __eventGroup.listener().onExceptionCaught(e, _session); } catch (Throwable ex) { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex)); } } }); } else { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } }; __processors[_idx].start(); } } @Override protected void __doRegisterEvent() throws IOException { for (NioEventProcessor _processor : __processors) { _processor.registerEvent(__channel, SelectionKey.OP_READ, new NioSession<NioUdpListener>(this, __channel) { @Override protected int __doChannelRead(ByteBuffer buffer) throws IOException { SocketAddress _address = ((DatagramChannel) __channel).receive(buffer); if (_address != null) { attr(SocketAddress.class.getName(), _address); return __buffer.remaining(); } return 0; } @Override protected int __doChannelWrite(ByteBuffer buffer) throws IOException { SocketAddress _address = attr(SocketAddress.class.getName()); if (_address != null) { return ((DatagramChannel) __channel).send(buffer, _address); } buffer.reset(); return 0; } }); } } }; __eventGroup.start(); // _LOG.info("UdpServer [" + __eventGroup.name() + "] started at " + __serverCfg.getServerHost() + ":" + __serverCfg.getPort()); } }
From source file:org.apache.axis2.transport.udp.IODispatcher.java
/** * Add a new endpoint. This method creates a new socket listening on * the UDP port specified in the endpoint description and makes sure * that incoming packets are routed to the specified service. * //from w w w . j av a 2 s . c o m * @param endpoint the endpoint description * @throws IOException if the socket could not be created or * registered with the selector */ public void addEndpoint(final Endpoint endpoint) throws IOException { final DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(endpoint.getPort())); channel.configureBlocking(false); execute(new SelectorOperation() { @Override public void doExecute(Selector selector) throws IOException { channel.register(selector, SelectionKey.OP_READ, endpoint); } }); log.info("UDP endpoint started on port : " + endpoint.getPort()); }
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); 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"); }//from www. j ava2 s . co m } dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); dChannel.bind(new InetSocketAddress(nicIPAddress, port)); return dChannel; }