?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
바로 이어서 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
No. Category Subject Author Date Views
469 Develop [ios] APNS, Remote Push 수신 시점에서 앱의 3가지 실행 상태 hooni 2018.10.19 963
468 Develop [ios] APNS, Remote Push 사용자가 수신을 동의했는지 확인하기 hooni 2018.10.19 1248
467 Develop [ios] APNS 클라이언트 구현 (pdf) file hooni 2013.06.27 15687
466 Develop [ios] APNS 샘플 코드.. secret hooni 2013.06.27 0
465 Develop [ios] AES256 알고리즘을 이용해 데이터 암호화/복호화 방법 file hooni 2015.07.21 4099
464 Develop [ios] @property의 속성 (strong, weak, copy) 사용 경우 hooni 2014.08.08 1653
463 Develop [ios] UIView 계층구조 hooni 2015.01.03 1122
462 Etc [htm] DOM에 대해 ㅎㅎ file hooni 2003.04.23 14717
461 Develop [html] 캐쉬된 웹페이지 사용하지 않도록 하는 방법 hooni 2003.04.23 13028
460 Develop [html] 메타태그 사용예.. 은지나 바라~ hooni 2003.04.23 7225
459 Develop [html] SVG(Scalable Vector Graphics) 간단 정리 hooni 2014.02.13 8829
458 Develop [html] HTML5 튜토리얼 링크 ㅋㅋ hooni 2013.04.23 12809
457 Develop [git] 쉬운 버전관리 Git 설명 hooni 2015.08.18 870
456 Etc [flash] 페이지 이동 (액션스크립트) file hooni 2013.04.23 16263
455 Etc [flash] 자동차 엔진의 원리 (4행정 사이클 그림) file hooni 2013.04.23 21222
454 Etc [flash] 맘에 드는 파이차트 file hooni 2013.04.23 12590
Board Pagination Prev 1 ... 43 44 45 46 47 ... 74 Next
/ 74