![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e173. Creating a Non-Blocking SocketThis example shows how to create a non-blocking socket. A non-blocking socket requires a socket channel.See also e176 Using a Selector to Manage Non-Blocking Sockets. // Creates a non-blocking socket channel for the specified host name and port. // connect() is called on the new channel before it is returned. public static SocketChannel createSocketChannel(String hostName, int port) throws IOException { // Create a non-blocking socket channel SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); // Send a connection request to the server; this method is non-blocking sChannel.connect(new InetSocketAddress(hostName, port)); return sChannel; } // Create a non-blocking socket and check for connections try { // Create a non-blocking socket channel on port 80 SocketChannel sChannel = createSocketChannel("hostname.com", 80); // Before the socket is usable, the connection must be completed // by calling finishConnect(), which is non-blocking while (!sChannel.finishConnect()) { // Do something else } // Socket channel is now ready to use } catch (IOException e) { }
e175. Writing to a SocketChannel e176. Using a Selector to Manage Non-Blocking Sockets e177. Creating a Non-Blocking Server Socket e178. Accepting a Connection on a ServerSocketChannel e179. Using a Selector to Manage Non-Blocking Server Sockets e180. Detecting When a Non-Blocking Socket Is Closed by the Remote Host
© 2002 Addison-Wesley. |