조회 수 2131 추천 수 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
번호 분류 제목 글쓴이 날짜 조회 수
681 Develop [css] z-index에 설정할 수 있는 최대값? hooni 2013.12.20 14793
680 Develop [ios] Objective-C에서 SQLite 사용하기.. file hooni 2013.04.23 14580
679 Develop [ios] iOS In App Purchase #1 (코드 구현 전 웹 설정 작업) file hooni 2013.11.20 14553
678 Develop [c] 메시지큐(Message Queue) 설명.. (joinc) hooni 2013.04.23 14302
677 Develop [c] vc++ 에서 clrscr(), gotoxy() 함수 사용하기.. hooni 2013.04.23 14290
676 Develop [C] C언어의 조건 연산자(Conditional Operator) hooni 2003.04.23 14284
675 Develop [c] 64bit 머신에서 inet_ntoa() 사용시 Segment fault 대처 방법법 hooni 2014.02.08 14261
674 Develop [c] 민수형 libipq 샘플 소스 ㅋㅋ hooni 2003.04.23 14145
673 Develop OPT와 CAS에 대한 자료.. (교수님 메일로 보내드린 자료..) file hooni 2013.04.23 13974
672 Develop [ios] Hybrid 앱 스터디 발표 자료 file hooni 2013.09.06 13813
671 Develop [ios] iOS In App Purchase #2 (코드 구현) file hooni 2013.11.20 13809
670 Develop [jsp] Get방식, Post방식 전송 예제.. file hooni 2003.04.23 13799
669 Develop [iphone] 아이폰 어플 모음 ㅋㅋ secret hooni 2013.04.23 13707
668 Develop [js] window.open() 속성 사용 방법 hooni 2013.11.18 13635
667 Develop [js] 자바스크립트를 동적으로 로딩하기 hooni 2013.04.23 13612
666 Develop [c++] mfc 간단한 파일 입출력 예제 hooni 2013.04.23 13559
Board Pagination Prev 1 ... 9 10 11 12 13 ... 53 Next
/ 53