티스토리 뷰

Developer

java server framework netty

rocksea 2013. 1. 7. 11:19

비동기 이벤트드리븐기반 네트워크 어플리케이션 서버 네티 (an asynchronous event-driven network application framework ) 에 대해 알아보기로 하겠습니다. netty가 국내에서 더 유명한데 이유는 java 개발자로 트위서에 근무하시는 이희승씨가 참여해서 입니다. 

우선 netty의 architecture 를 살펴보도록 하겠습니다.


[ 그림1 ] Netty Architecture


socket, http & web socket, SSL/TLS 등을 지원합니다.


간단한 echo server tutorial 하나 돌려보도록 하겠습니다.

NettyServer.java

import java.net.InetSocketAddress;

import java.util.concurrent.Executors;


import org.jboss.netty.bootstrap.ServerBootstrap;

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.NioServerSocketChannelFactory;

import org.apache.log4j.Logger;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


import co.kr.lgcns.viper.account.service.TokenService;


/**

 * @author rocksea

 *

 */

public class NettyServer {

private static Logger logger = Logger.getLogger(NettyServer.class);


private final int port;


/**

 * @param port

 */

public NettyServer(int port) {

  this.port = port;

}


/**

 * 

 */

public void run() {

  // Configure the server.

  ServerBootstrap bootstrap = new ServerBootstrap(

          new NioServerSocketChannelFactory(

                  Executors.newCachedThreadPool(),

                  Executors.newCachedThreadPool()));


  // Set up the pipeline factory.

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

      public ChannelPipeline getPipeline() throws Exception {

          return Channels.pipeline(new NettyServerHandler());

      }

  });


  // Bind and start to accept incoming connections.

  bootstrap.bind(new InetSocketAddress("0.0.0.0",port));


  

}


/**

 * @param args

 * @throws Exception

 */

public static void main(String[] args) throws Exception {

 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

 int port;

 if (args.length > 0) {

     port = Integer.parseInt(args[0]);

 } else {

     port = 8080;

 }

 

 logger.debug("start main...");

 new NettyServer(port).run();

}

}


NettyServerHandler.java

import java.util.concurrent.atomic.AtomicLong;


import org.jboss.netty.buffer.ChannelBuffer;

import static org.jboss.netty.buffer.ChannelBuffers.*;

import org.jboss.netty.channel.Channel;

import org.jboss.netty.channel.ChannelHandlerContext;

import org.jboss.netty.channel.ExceptionEvent;

import org.jboss.netty.channel.MessageEvent;

import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import org.apache.log4j.Logger;


import co.kr.lgcns.viper.account.proc.DataParseProc;

import co.kr.lgcns.viper.account.service.TokenService;



/**

 * Handler implementation for the echo server.

 */

public class NettyServerHandler extends SimpleChannelUpstreamHandler {

private Logger logger = Logger.getLogger(NettyServerHandler.class);


    private final AtomicLong transferredBytes = new AtomicLong();


    /**

     * @return

     */

    public long getTransferredBytes() {

        return transferredBytes.get();

    }


    /* (non-Javadoc)

     * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)

     */

    @Override

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

        // Send back the received message to the remote peer.

        transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());

        

        ChannelBuffer buf = dynamicBuffer(10);

        //ChannelBuffer buf = buffer(10);

        logger.debug("SEND PACKET::"+(new String(((ChannelBuffer)e.getMessage()).array())));


        e.getChannel().write(e.getMessage());

        e.getChannel().close();

        

    }

    

    /* (non-Javadoc)

     * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent)

     */

    @Override

    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {

        // Close the connection when an exception is raised.

        logger.info("Unexpected exception from downstream."+ e.getCause());

        e.getChannel().close();

    }

}




출처 : https://netty.io


다음번엔 SSL기반의 socket server를 만들어 보도록 하겠습니다.


.by rocksea



'Developer' 카테고리의 다른 글

[ netty ] 1024byte 이상의 data 전송시 문제.  (2) 2013.01.15
[svn] SSL Handshaking failed.  (0) 2013.01.14
ubuntu에서 windows remote desktop 접속.  (0) 2013.01.03
maven ms-sql dependency 추가  (0) 2012.12.26
chrome browser 설치하기  (0) 2012.12.20
댓글