?

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
853 Etc 영어. 반드시 외워야 할 영어 숙어 2 file hooni 2016.07.07 6326
852 Develop [c][php] 프로세스정보와 메모리 정보 웹으로 출력하는거.. file hooni 2013.04.23 6331
851 Develop [js] 사진첩에 쓸 내용 - 마우스 오버로 바꾸기 hooni 2013.04.23 6338
850 Develop [c] 다중연결 서버 만들기 #3 - poll() 사용 file hooni 2013.04.23 6340
849 Develop [java] 채팅창 처럼2.. swing.. file hooni 2013.04.23 6421
848 Develop [doc] C언어 문법 설명서 file hooni 2013.04.23 6437
847 Develop [php] 정규표현식 간단히 정리 hooni 2013.04.23 6453
846 Develop [c] 메세지 프로그램 (Server - Agent - Client) file hooni 2013.04.23 6457
845 Develop [js] 윤동이가 만든 영어 학습(?) 프로그램 file hooni 2013.04.23 6462
844 Develop [c] 네트워크 보안 프로그래밍 과제 (Server,Agent,Client) file hooni 2013.04.23 6472
843 Develop [js] 새로고침(refresh)방법과 다른 페이지 바꾸기.. hooni 2003.04.23 6521
842 Develop [c] 민수형 소스(도메인소켓포함) file hooni 2013.04.23 6522
841 Develop [c] 간단한 점 이동 샘플 소스코드 hooni 2013.04.23 6541
840 Develop [c] 웅지학원 NAT를 소스코드로.. file hooni 2013.04.23 6611
839 Develop [c++] 인라인 함수 설명과 예제.. file hooni 2013.04.23 6633
838 Develop [js] 스타크래프트(starcraft).. file hooni 2013.04.23 6640
Board Pagination Prev 1 ... 19 20 21 22 23 ... 74 Next
/ 74