import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* NIO 소켓 예제.<P>
* JDK 1.7 부터 지원<br/>
* 그 전버전을 이용한다면 Thread 상속 받아 Selector 에서 계속 값 작업 하는 구조로 가야 했지만 이건 아주 심플해짐.
*/
public class AsynchronousServerSocketChannelSample {
private AsynchronousSocketChannel client;
public AsynchronousServerSocketChannelSample(String host, int port) throws IOException {
this.client = AsynchronousSocketChannel.open();
final Future<Void> connectRes = this.client.connect( new InetSocketAddress(host, port) );
try {
connectRes.get(10L, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
System.out.println("Connection Error " + e.getMessage());
}
System.out.println("Connection complete");
}
private String sendMessage(String message) throws InterruptedException, ExecutionException, TimeoutException {
if( ! this.client.isOpen() ) {
throw new InterruptedException();
}
final Future<Integer> writeResult = this.client.write(ByteBuffer.wrap(message.getBytes()));
Integer i = writeResult.get(10L, TimeUnit.SECONDS);
System.out.println(i);
final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
readBuffer.clear();
final Future<Integer> readResult = this.client.read(readBuffer);
final Integer readSize = readResult.get(10L, TimeUnit.SECONDS);
final byte [] readValue = new byte[readSize];
System.arraycopy(readBuffer.array(), 0, readValue, 0, readSize);
return new String(readValue);
}
private void disconnection() {
try {
this.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
final AsynchronousServerSocketChannelSample sample = new AsynchronousServerSocketChannelSample("localhost", 15301);
String res;
try {
res = sample.sendMessage("puhahahaha");
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
res = e.getMessage();
}
System.out.println( res );
sample.disconnection();
System.out.println( "End" );
}
}