37 lines
1.4 KiB
Java
37 lines
1.4 KiB
Java
Creating a Non-Blocking Socket
|
|
|
|
public class test
|
|
{
|
|
public static void main(String args[])
|
|
{
|
|
// Create a non-blocking socket and check for connections
|
|
try {
|
|
// Create a non-blocking socket channel on port 8080
|
|
SocketChannel sChannel = createSocketChannel("www.xxx", 8080);
|
|
|
|
// Before the socket is usable, the connection must be completed
|
|
// by calling finishConnect(), which is non-blocking
|
|
while (!sChannel.finishConnect()) {
|
|
// Do something else
|
|
System.out.println("wonderful");
|
|
}
|
|
// Socket channel is now ready to use
|
|
}
|
|
catch (IOException e) {
|
|
}
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
}
|