public abstract boolean isBlocking(); public abstract Object blockingLock();
returning a java.net.Socket object. On the other hand, the accept() method of ServerSocketChannel returns objects of type SocketChannel and is capable of operating in nonblocking mode. If a security manager is in place, both methods perform the same security checks. If invoked in nonblocking mode, ServerSocketChannel.accept() will immediately return null if no incoming connections are currently pending. This ability to check for connections without getting stuck is what enables scalability and reduces complexity. Selectability also comes into play. A ServerSocketChannel object can be registered with a Selector instance to enable notification when new connections arrive. Example 3-7 demonstrates how to use a nonblocking accept(). Example 3-7. A nonblocking accept() with ServerSocketChannel package com.ronsoft.books.nio.channels; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.net.InetSocketAddress; /** * Test nonblocking accept() using ServerSocketChannel. * Start this program, then “telnet localhost 1234″ to * connect to it. * * @author Ron Hitchens (ron@ronsoft.com) */ public class ChannelAccept{ public static final String GREETING = “Hello I must be going.rn”; public static void main (String [] argv) throws Exception { int port = 1234; // default if (argv.length > 0) { port = Integer.parseInt (argv [0]); } ByteBuffer buffer = ByteBuffer.wrap (GREETING.getBytes()); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind (new InetSocketAddress (port)); ssc.configureBlocking (false); while (true) { System.out.println (”Waiting for connections”); SocketChannel sc = ssc.accept(); if (sc == null) { // no connections, snooze a while 106
Hint: This post is supported by Gama web hosting hrvatska services