조회 수 2045 추천 수 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
번호 분류 제목 글쓴이 날짜 조회 수
469 System/OS [linux] 데비안(debian.org) 리눅스 명령어 예제 hooni 2006.04.23 10424
468 System/OS [doc] 레드햇 리눅스 메뉴얼 (html버전) file hooni 2013.04.23 10452
467 System/OS [linux] SSH에 대한 기본 설명과 설치/설정 hooni 2013.04.23 10500
466 Develop [php] 날짜 정보 출력 (년,월,일,시,분,초) hooni 2013.04.23 10517
465 Develop [php] GregorianToJD(), JDToGregorian() 함수 내용 hooni 2013.12.25 10596
464 System/OS [perl] 영규가 만든 스크립트.. 하하.. hooni 2013.04.23 10597
463 Develop [js] jQuery plugin 요약 hooni 2013.12.20 10703
462 Develop [c++]현승이가 보내준 암호화 모듈 AES라인델.. file hooni 2003.04.23 10715
461 Develop [c++] p.118 확인학습 5번 hooni 2003.04.23 10734
460 Develop [c++] 가짜 인증서(하나은행) 프로그램 file hooni 2013.04.23 10761
459 System/OS [linux] 프로세스의 stat 상태에 대한 설명 hooni 2013.04.23 10762
458 System/OS [mysql] 시간 관련 SQL구문.. hooni 2013.04.23 10775
457 Develop [php] XE 관리자 IP대역 설정 오류 해결법 hooni 2014.02.10 10778
456 System/OS OSI (Open Systems Interconnection) 개방형 시스템간 상호 접속 file hooni 2013.04.23 10787
455 Develop [unix] 로그파일 정리 쉘스크립트 hooni 2014.02.19 10806
454 Develop [c] 거리와 각도를 입력받아서 좌표로 변환 file hooni 2013.04.23 10814
Board Pagination Prev 1 ... 43 44 45 46 47 ... 74 Next
/ 74