조회 수 2130 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
바로 이어서 client 로직을 올려 봅니다.
 
여기도 2개의 클래스 입니다.
 
첫 번째로 이벤트 핸들러 클래스 입니다.
package com.incross.netty;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class SimpleClientHandler extends SimpleChannelHandler
{
  @Override
  public void messageReceived(ChannelHandlerContext ctx,MessageEvent e)
  {
    ChannelBuffer response  =   (ChannelBuffer)e.getMessage();
    byte[] message    =   response.array();
    
    System.out.println("message:"+new String(message));
    //response 메시지 찍어보기
    
    if(new String(message).equals("server write test"))
    {
      //어떤 조건이 들어왔을 때 종료 되는 로직
      Channel ch     =   e.getChannel();
      ch.close();
      System.out.println("closed");
    }
  }
 
  //connection 연결 하면 바로 데이터 전송 하도록 하는 메소드
  @Override
  public void channelConnected(ChannelHandlerContext ctx,ChannelStateEvent e)
  {
    Channel ch     =   e.getChannel();
    ChannelBuffer buf   =   ChannelBuffers.dynamicBuffer();
    buf.writeBytes("1234a".getBytes());
    ChannelFuture future  =   ch.write(buf);
    
    future.addListener(new ChannelFutureListener()
    {
      public void operationComplete(ChannelFuture future)
      {
        Channel ch  =  future.getChannel();
        //ch.close();
        //보내고 응답 안받고 끝내려면 close 해주면 됨
      }
    });
  }

  public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e)
  {
    e.getCause().printStackTrace();
    Channel ch     =   e.getChannel();
    ch.close();
  }
}

두 번째로 클라이언트 쪽의 main 클래스 입니다.
package com.incross.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class SimpleClient
{
  /**
  * @param args
  */
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
    int port   =   8000;
    ChannelFactory factory   =   new NioClientSocketChannelFactory(
                                    Executors.newCachedThreadPool(),
                                    Executors.newCachedThreadPool()              
                                );
  
    ClientBootstrap bootstrap  =   new ClientBootstrap(factory);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

      @Override
      public ChannelPipeline getPipeline() throws Exception
      {
        // TODO Auto-generated method stub
        return Channels.pipeline(new SimpleClientHandler()); 
      }
    });
  
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    ChannelFuture future   =   bootstrap.connect(new InetSocketAddress("localhost",port));
  
    // 아래 부터는  connection 끊어 졌을 때를 위한 처리
    future.awaitUninterruptibly();
  
    if(!future.isSuccess())
    {
      future.getCause().printStackTrace();
    }

    future.getChannel().getCloseFuture().awaitUninterruptibly();
    factory.releaseExternalResources();
    //connection 끊어졌을 때 자원 회수
  }
}

[출처] http://shonm.tistory.com/398
?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
261 Develop [c] 간단한 점 이동 샘플 소스코드 hooni 2013.04.23 6583
260 Develop [c] 간단한 자료구조(stack, queue, linked list) 구현 소스 6 file hooni 2003.04.23 10164
259 Develop [c] 간단한 순위 루틴.. (질문에 대한 답변) hooni 2003.04.23 7495
258 Develop [c] 간단한 순위 루틴.. (정보처리기사) hooni 2003.04.23 6905
257 Develop [c] 간단한 소켓 프로그래밍 샘플 file hooni 2013.04.23 8187
256 Develop [c] 간단한 링크드 리스트(linked list) 자료형 예제.. hooni 2003.04.23 9863
255 Develop [c] 가위 바위 보 서버, 클라이언트 소스코드 file hooni 2003.04.23 8216
254 Develop [c] 가변인자 함수(printf와 같은..) hooni 2013.04.23 7199
253 Develop [c] vc++ 에서 clrscr(), gotoxy() 함수 사용하기.. hooni 2013.04.23 14286
252 Develop [c] UTF-8을 EUC-KR로 변환.. (iconv) file hooni 2013.04.23 20198
251 Develop [c] Unix Domain Socket 을 이용한 IPC hooni 2013.04.23 8042
250 Develop [c] UCP/TCP 채팅 소스 - 정리해야 함.. file hooni 2003.04.23 7947
249 Develop [c] SetTimer() & KillTimer() & 일회용 Timer hooni 2013.04.23 9236
248 Develop [c] selec()를 이용한 입출력 다중화 file hooni 2013.04.23 8272
247 Develop [c] scanf(), printf() 포맷의 형변환 hooni 2003.04.23 10897
246 Develop [c] RSA 암호화 구현(gmp 라이브러리 활용) file hooni 2016.10.03 1014
Board Pagination Prev 1 ... 56 57 58 59 60 ... 74 Next
/ 74