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