게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
[java] NIO Socket 예제
게시물ID : programmer_22744짧은주소 복사하기
작성자 : 봄아
추천 : 0
조회수 : 860회
댓글수 : 0개
등록시간 : 2018/12/18 15:07:54
옵션
  • 창작글
  • 본인삭제금지
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" );
       
    }
   

}

전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호