public static void main (String [] argv) throws

public static void main (String [] argv) throws Exception { String host = “localhost”; int port = 80; if (argv.length == 2) { host = argv [0]; port = Integer.parseInt (argv [1]); } InetSocketAddress addr = new InetSocketAddress (host, port); SocketChannel sc = SocketChannel.open(); sc.configureBlocking (false); System.out.println (”initiating connection”); sc.connect (addr); while ( ! sc.finishConnect()) { doSomethingUseful(); } System.out.println (”connection established”); // Do something with the connected socket // The SocketChannel is still nonblocking sc.close(); } private static void doSomethingUseful() { System.out.println (”doing something useless”); } } If an asynchronous-connection attempt fails, the next invocation of finishConnect() throws an appropriate checked exception to indicate the nature of the problem. The channel will then be closed and cannot be connected or used again. The connection-related methods provide ways to poll a channel and determine its status while a connection is in progress. In Chapter 4, we’ll see how to use Selectors to avoid polling and receive notification when an asynchronous connection has been established. Socket channels are thread-safe. Multiple threads do not need to take special steps to protect against concurrent access, but only one read and one write operation will be in progress at any given time. Keep in mind that sockets are stream-oriented, not packet-oriented. They guarantee that the bytes sent will arrive in the same order but make no promises about maintaining groupings. A sender may write 20 bytes to a socket, and the receiver gets only 3 of those bytes when invoking read(). The remaining 17 bytes 110
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

Comments are closed.