List of usage examples for java.nio.channels SelectionKey isReadable
public final boolean isReadable()
From source file:MainClass.java
public static void main(String[] args) throws IOException { Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); ByteBuffer buffer = ByteBuffer.allocate(512); Selector selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8000)); server.configureBlocking(false);/* w w w . j a v a 2 s. c o m*/ SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT); for (;;) { selector.select(); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); if (key == serverkey) { if (key.isAcceptable()) { SocketChannel client = server.accept(); client.configureBlocking(false); SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ); clientkey.attach(new Integer(0)); } } else { SocketChannel client = (SocketChannel) key.channel(); if (!key.isReadable()) continue; int bytesread = client.read(buffer); if (bytesread == -1) { key.cancel(); client.close(); continue; } buffer.flip(); String request = decoder.decode(buffer).toString(); buffer.clear(); if (request.trim().equals("quit")) { client.write(encoder.encode(CharBuffer.wrap("Bye."))); key.cancel(); client.close(); } else { int num = ((Integer) key.attachment()).intValue(); String response = num + ": " + request.toUpperCase(); client.write(encoder.encode(CharBuffer.wrap(response))); key.attach(new Integer(num + 1)); } } } } }
From source file:GetWebPageApp.java
public static void main(String args[]) throws Exception { String resource, host, file;/*w w w .j av a 2 s .com*/ int slashPos; resource = "www.java2s.com/index.htm"; // skip HTTP:// slashPos = resource.indexOf('/'); // find host/file separator if (slashPos < 0) { resource = resource + "/"; slashPos = resource.indexOf('/'); } file = resource.substring(slashPos); // isolate host and file parts host = resource.substring(0, slashPos); System.out.println("Host to contact: '" + host + "'"); System.out.println("File to fetch : '" + file + "'"); SocketChannel channel = null; try { Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); CharBuffer charBuffer = CharBuffer.allocate(1024); InetSocketAddress socketAddress = new InetSocketAddress(host, 80); channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(socketAddress); selector = Selector.open(); channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); while (selector.select(500) > 0) { Set readyKeys = selector.selectedKeys(); try { Iterator readyItor = readyKeys.iterator(); while (readyItor.hasNext()) { SelectionKey key = (SelectionKey) readyItor.next(); readyItor.remove(); SocketChannel keyChannel = (SocketChannel) key.channel(); if (key.isConnectable()) { if (keyChannel.isConnectionPending()) { keyChannel.finishConnect(); } String request = "GET " + file + " \r\n\r\n"; keyChannel.write(encoder.encode(CharBuffer.wrap(request))); } else if (key.isReadable()) { keyChannel.read(buffer); buffer.flip(); decoder.decode(buffer, charBuffer, false); charBuffer.flip(); System.out.print(charBuffer); buffer.clear(); charBuffer.clear(); } else { System.err.println("Unknown key"); } } } catch (ConcurrentModificationException e) { } } } catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } finally { if (channel != null) { try { channel.close(); } catch (IOException ignored) { } } } System.out.println("\nDone."); }
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();//from w w w . j av a 2s . c o 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:PrintServiceWebInterface.java
public static void main(String[] args) throws IOException { // Get the character encoders and decoders we'll need Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); // The HTTP headers we send back to the client are fixed String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n"; // We'll use two buffers in our response. One holds the fixed // headers, and the other holds the variable body of the response. ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = encoder.encode(CharBuffer.wrap(headers)); ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024); buffers[1] = body;//from www. j a va 2 s .c om // Find all available PrintService objects to describe PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); // All of the channels we use in this code will be in non-blocking // mode. So we create a Selector object that will block while // monitoring all of the channels and will only stop blocking when // one or more of the channels is ready for I/O of some sort. Selector selector = Selector.open(); // Create a new ServerSocketChannel, and bind it to port 8000. // Note that we have to do this using the underlying ServerSocket. ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8000)); // Put the ServerSocketChannel into non-blocking mode server.configureBlocking(false); // Now register the channel with the Selector. The SelectionKey // represents the registration of this channel with this Selector. SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT); for (;;) { // The main server loop. The server runs forever. // This call blocks until there is activity on one of the // registered channels. This is the key method in non-blocking I/O. selector.select(); // Get a java.util.Set containing the SelectionKey objects for // all channels that are ready for I/O. Set keys = selector.selectedKeys(); // Use a java.util.Iterator to loop through the selected keys for (Iterator i = keys.iterator(); i.hasNext();) { // Get the next SelectionKey in the set, and then remove it // from the set. It must be removed explicitly, or it will // be returned again by the next call to select(). SelectionKey key = (SelectionKey) i.next(); i.remove(); // Check whether this key is the SelectionKey we got when // we registered the ServerSocketChannel. if (key == serverkey) { // Activity on the ServerSocketChannel means a client // is trying to connect to the server. if (key.isAcceptable()) { // Accept the client connection, and obtain a // SocketChannel to communicate with the client. SocketChannel client = server.accept(); // Make sure we actually got a connection if (client == null) continue; // Put the client channel in non-blocking mode. client.configureBlocking(false); // Now register the client channel with the Selector, // specifying that we'd like to know when there is // data ready to read on the channel. SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ); } } else { // If the key we got from the Set of keys is not the // ServerSocketChannel key, then it must be a key // representing one of the client connections. // Get the channel from the key. SocketChannel client = (SocketChannel) key.channel(); // If we got here, it should mean that there is data to // be read from the channel, but we double-check here. if (!key.isReadable()) continue; // Now read bytes from the client. We assume that // we get all the client's bytes in one read operation client.read(body); // The data we read should be some kind of HTTP GET // request. We don't bother checking it however since // there is only one page of data we know how to return. body.clear(); // Build an HTML document as our reponse. // The body of the document contains PrintService details StringBuffer response = new StringBuffer(); response.append( "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>"); for (int s = 0; s < services.length; s++) { PrintService service = services[s]; response.append("<h2>").append(service.getName()).append("</h2><table>"); Attribute[] attrs = service.getAttributes().toArray(); for (int a = 0; a < attrs.length; a++) { Attribute attr = attrs[a]; response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr) .append("</tr>"); } response.append("</table>"); } response.append("</body></html>\r\n"); // Encode the response into the body ByteBuffer encoder.reset(); encoder.encode(CharBuffer.wrap(response), body, true); encoder.flush(body); body.flip(); // Prepare the body buffer to be drained // While there are bytes left to write while (body.hasRemaining()) { // Write both header and body buffers client.write(buffers); } buffers[0].flip(); // Prepare header buffer for next write body.clear(); // Prepare body buffer for next read // Once we've sent our response, we have no more interest // in the client channel or its SelectionKey client.close(); // Close the channel. key.cancel(); // Tell Selector to stop monitoring it. } } } }
From source file:Main.java
public static boolean processReadySet(Set readySet) throws Exception { Iterator iterator = readySet.iterator(); while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); iterator.remove();//ww w . j a v a 2 s . co m if (key.isConnectable()) { boolean connected = processConnect(key); if (!connected) { return true; // Exit } } if (key.isReadable()) { String msg = processRead(key); System.out.println("[Server]: " + msg); } if (key.isWritable()) { System.out.print("Please enter a message(Bye to quit):"); String msg = userInputReader.readLine(); if (msg.equalsIgnoreCase("bye")) { return true; // Exit } SocketChannel sChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); sChannel.write(buffer); } } return false; // Not done yet }
From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java
protected void read(SelectionKey selectionKey, Consumer<List<String>> callback, Consumer<Exception> exceptionHandler) { try {//ww w . j a v a 2 s . c o m if (!selectionKey.isValid() || !selectionKey.isReadable()) return; byteBuffer.clear(); int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer); if (bytesRead < 0) { LOG.warn( "End of stream reached. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream")); return; } byteBuffer.flip(); if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) { LOG.error("Max message size of " + maxMessageSize + " bytes exceeded. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded")); return; } while (byteBuffer.hasRemaining()) messageBuffer.write(byteBuffer.get()); String messagesString = messageBuffer.toString(charset); messageBuffer.reset(); List<String> messages = new ArrayList<>(); for (String message : splitter.split(messagesString)) messages.add(message); messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset)); if (!messages.isEmpty()) { selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ); callback.accept(messages); } } catch (Exception e) { LOG.error("ReadDelimitedMessage task failed", e); invokeExceptionHandler(selectionKey, exceptionHandler, e); } }
From source file:org.apache.axis2.transport.udp.IODispatcher.java
/** * Run the I/O dispatcher./* ww w . j a v a 2 s .co m*/ * This method contains the event loop that polls the selector, reads the incoming * packets and dispatches the work. * It only returns when {@link #stop()} is called. */ public void run() { while (true) { try { selector.select(); } catch (IOException ex) { log.error("Exception in select; I/O dispatcher will be shut down", ex); return; } // Execute pending selector operations while (true) { SelectorOperation request = selectorOperationQueue.poll(); if (request == null) { break; } request.execute(selector); if (!selector.isOpen()) { return; } } for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) { SelectionKey key = it.next(); it.remove(); if (key.isValid() && key.isReadable()) { receive((Endpoint) key.attachment(), (DatagramChannel) key.channel()); } } } }
From source file:me.schiz.jmeter.ring.udp.EventLoopRunnable.java
@Override public void run() { log.info("EventLoop started in " + Thread.currentThread().getName()); int events_count, register_count; while (true) { try {// w ww .j a va2 s .co m if (!selector.isOpen()) break; try { events_count = selector.select(POLL_TIMEOUT); } catch (ClosedSelectorException e) { log.error("Selector is closed", e); break; } register_count = registerQueue.size(); if (register_count > 0) registerCallback(register_count); if (events_count == 0) continue; Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); DatagramChannel dc = (DatagramChannel) key.channel(); try { if (key.isReadable()) readCallback(dc); } catch (CancelledKeyException e) { log.error("cancelled key exception", e); Token t = ring.get(dc); if (t != null) { t.lock.lock(); ring.reset(t.id); t.lock.unlock(); } } it.remove(); } } catch (IOException e) { log.error("IOException", e); break; } } byteBuffer.clear(); log.info("EventLoop in " + Thread.currentThread().getName() + " has stopped"); }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processSelectedKeys(Set<SelectionKey> keys) throws Exception { Iterator<SelectionKey> itr = keys.iterator(); while (itr.hasNext()) { SelectionKey key = itr.next(); if (key.isReadable()) { processRead(key);/*from w w w.jav a 2 s .c o m*/ } if (key.isWritable()) { processWrite(key); } if (key.isConnectable()) { processConnect(key); } if (key.isAcceptable()) { ; } itr.remove(); } }
From source file:voldemort.common.nio.SelectorManagerWorker.java
public void run() { try {//from w w w. jav a 2 s . c o m SelectionKey selectionKey = socketChannel.keyFor(selector); if (selectionKey.isConnectable()) connect(selectionKey); else if (selectionKey.isReadable()) read(selectionKey); else if (selectionKey.isWritable()) write(selectionKey); else if (!selectionKey.isValid()) throw new IllegalStateException("Selection key not valid for " + socketChannel.socket()); else throw new IllegalStateException( "Unknown state, not readable, writable, or valid for " + socketChannel.socket()); } catch (ClosedByInterruptException e) { reportException(e); close(); } catch (CancelledKeyException e) { close(); } catch (EOFException e) { // EOFException is expected, hence no logging, otherwise this block // could be combined with IOException reportException(e); close(); } catch (IOException e) { logger.info("Connection reset from " + socketChannel.socket() + " with message - " + e.getMessage()); reportException(e); close(); } catch (Throwable t) { logger.error("Caught throwable from " + socketChannel.socket(), t); close(); } }