거꾸로 바라본 세상
반응형

NIO TCP blocking channel 소켓서버 & 클라이언트



서버 소켓 생성

ServerSocketChannel sock = ServerSocketChannel.open();

sock.configureBlocking(true);

sock.bind(new InetSocketAddress(9190));


요청기다림

SocketChannel socketChannel = sock.accept();


클라이언트 소켓 생성

SocketChannel socketChannel = SocketChannel.open();

socketChannel.configureBlocking(true);

socketChannel.connect(new InetSocketAddress(9190));


서버 or 클라이언트로부터 정보 받기

socketChannel.read();


서버 or 클라이언트로부터 정보 보내기

socketChannel.write();


ex) 소켓 서버

ServerSocketChannel sock = ServerSocketChannel.open();

sock.configureBlocking(true);

sock.bind(new InetSocketAddress(9190));


ExecutorService executorService = Executors.newCachedThreadPool();

while (true) {

System.out.println("연결기다리기");

SocketChannel socketChannel = sock.accept();

InetSocketAddress addr = (InetSocketAddress) socketChannel.getRemoteAddress();

System.out.println("연결수락 : " + addr.getHostName());


String data = null;

Charset charset = Charset.forName("UTF-8");

ByteBuffer byteBuffer = ByteBuffer.allocate(100);

int len = socketChannel.read(byteBuffer);

byteBuffer.flip();

data += charset.decode(byteBuffer).toString();

System.out.println("request msg : " + data);

byteBuffer = charset.encode("hello world Client");

socketChannel.write(byteBuffer);

System.out.println("데이터 보내기 성공");

if (sock.isOpen()) {

sock.close();

break;

}

}



ex) 클라이언트

SocketChannel socketChannel = SocketChannel.open();

socketChannel.configureBlocking(true);

socketChannel.connect(new InetSocketAddress(9190));

System.out.println("연결성공");

Charset charset = Charset.forName("UTF-8");

ByteBuffer buffer = charset.encode("hello world");

socketChannel.write(buffer);

System.out.println("보내기성공");

buffer = ByteBuffer.allocate(100);

int len = socketChannel.read(buffer);

buffer.flip();

String data = charset.decode(buffer).toString();

System.out.println("받은 데이터 : "+ data);

if(socketChannel.isOpen()) {

socketChannel.close();

}


반응형

'Language > Java' 카테고리의 다른 글

[병렬프로그래밍] 6. 작업실행  (0) 2017.04.25
volatile 키워드  (0) 2017.04.13
비동기 파일채널  (0) 2017.03.29
NIO  (0) 2017.03.29
[JAVA NIO] WatchService(와치서비스)  (0) 2017.03.24
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!