반응형

해당 소스는 다운받은 Netty의 예제 폴더에 있습니다.


폴더 경로 : netty-3.6.6.Final\src\main\java\org\jboss\netty\example\echo



EchoServer.java

  

1 public class EchoServer {

  2  
  3     private final int port;
  4  
  5     public EchoServer(int port) {
  6         this.port = port; 
  7     } 
  8  
  9     public void run() {
 10         // Configure the server. 
 11         ServerBootstrap bootstrap = new ServerBootstrap(
 12                 new NioServerSocketChannelFactory(
 13                         Executors.newCachedThreadPool(), 
 14                         Executors.newCachedThreadPool())); 
 15  
 16         // Set up the pipeline factory. 
 17         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
 18             public ChannelPipeline getPipeline() throws Exception {
 19                 return Channels.pipeline(new EchoServerHandler());
 20             } 
 21         }); 
 22  
 23         // Bind and start to accept incoming connections. 
 24         bootstrap.bind(new InetSocketAddress(port));
 25     } 
 26  
 27     public static void main(String[] args) throws Exception {
 28         int port; 
 29         if (args.length > 0) {
 30             port = Integer.parseInt(args[0]);
 31         } else { 
 32             port = 8080; 
 33         } 
 34         new EchoServer(port).run(); 
 35     } 
 36 }

EchoServerHandler.java


1 public class EchoServerHandler extends SimpleChannelUpstreamHandler {

  2  
  3     private static final Logger logger = Logger.getLogger(
  4             EchoServerHandler.class.getName()); 
  5  
  6     private final AtomicLong transferredBytes = new AtomicLong();
  7  
  8     public long getTransferredBytes() {
  9         return transferredBytes.get(); 
 10     } 
 11  
 12     @Override 
 13     public void messageReceived(
 14             ChannelHandlerContext ctx, MessageEvent e) { 
 15         // Send back the received message to the remote peer. 
 16         transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
 17         e.getChannel().write(e.getMessage()); 
 18     } 
 19  
 20     @Override 
 21     public void exceptionCaught(
 22             ChannelHandlerContext ctx, ExceptionEvent e) { 
 23         // Close the connection when an exception is raised. 
 24         logger.log( 
 25                 Level.WARNING, 
 26                 "Unexpected exception from downstream.", 
 27                 e.getCause()); 
 28         e.getChannel().close(); 
 29     } 
 30 }






반응형

'Netty' 카테고리의 다른 글

[java][netty] Netty Korean User Group 주소  (0) 2013.05.27
반응형

자바를 이용한 서버를 만들어 사용해오다가 이희승님이 개발하신 오픈소스 자바 프레임워크 Netty를 알게됐습니다. 


한국인이 개발한 라이브러리지만 생각보다 한글 자료는 얼마 없네요. 


다행인 것은 개발자님이 직접 댓글을 달아주시는 Netty Korean User Group(바로가기) 이 있습니다. 


Netty를 처음 시작하시는 분들은 즐겨찾기에 등록해 두셔도 좋을것 같네요.






반응형

'Netty' 카테고리의 다른 글

[java][netty] netty를 이용한 echo server 예제  (0) 2013.05.27

+ Recent posts