public class NonBlockingTCPClient {
public static void main(String[] args) {
byte[] data =
"hello"
.getBytes();
SocketChannel channel =
null
;
try
{
channel = SocketChannel.open();
channel.configureBlocking(
false
);
if
(!channel.connect(
new
InetSocketAddress(InetAddress.getLocalHost(), 8899))) {
while
(!channel.finishConnect()) {
System.out.print(
"."
);
}
}
System.out.println(
"Connected to server..."
);
ByteBuffer writeBuffer = ByteBuffer.wrap(data);
ByteBuffer readBuffer = ByteBuffer.allocate(data.length);
int totalBytesReceived = 0;
int bytesReceived;
while
(totalBytesReceived < data.length) {
if
(writeBuffer.hasRemaining()) {
channel.write(writeBuffer);
}
if
((bytesReceived = channel.read(readBuffer)) == -1) {
throw
new
SocketException(
"Connection closed prematurely"
);
}
totalBytesReceived += bytesReceived;
System.out.print(
"."
);
}
System.out.println(
"Server said: "
+
new
String(readBuffer.array()));
}
catch
(IOException e) {
e.printStackTrace();
} finally {
try
{
if
(channel !=
null
) {
channel.close();
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
}