echo server, Java, netty, 예제
반응형
해당 소스는 다운받은 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 |
---|