Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. EventLoopGroup bossGroup = new NioEventLoopGroup();
  2. EventLoopGroup workerGroup = new NioEventLoopGroup();
  3. try {
  4. ServerBootstrap b = new ServerBootstrap();
  5. b.group(bossGroup, workerGroup)
  6. .channel(NioServerSocketChannel.class)
  7. .childHandler(new ServerInitializer());
  8.  
  9.  
  10. ChannelFuture f = b.bind(port).sync();
  11.  
  12. f.channel().closeFuture().sync();
  13. } finally {
  14. workerGroup.shutdownGracefully();
  15. bossGroup.shutdownGracefully();
  16. }
  17. ///////////////////////////////////
  18. public class ServerInitializer extends ChannelInitializer<SocketChannel> {
  19. @Override
  20. protected void initChannel(SocketChannel ch) throws Exception {
  21. final ChannelPipeline p = ch.pipeline();
  22. p.addLast("decoder", new InputDecoder());
  23. p.addLast("encoder", new OutputEncoder());
  24. p.addLast("handler", new ServerHandler());
  25. p.addLast("httpExceptionHandler", new ServerExceptionHandler());
  26. }
  27. }
  28. ///////////////////////////////////
  29. public class ServerHandler extends SimpleChannelInboundHandler<String> {
  30. @Override
  31. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception{
  32. ChannelFuture f = ctx.writeAndFlush(msg);
  33. try {
  34. f.channel().closeFuture().sync();
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40.  
  41. EventLoopGroup workerGroup = new NioEventLoopGroup();
  42.  
  43. try {
  44. Bootstrap b = new Bootstrap();
  45. b.group(workerGroup);
  46. b.channel(NioSocketChannel.class);
  47. b.handler(new ClientInitializer());
  48.  
  49. Channel ch = b.connect(host, port).sync().channel();
  50. ChannelFuture f = ch.writeAndFlush("Some message");
  51.  
  52. } finally {
  53. workerGroup.shutdownGracefully();
  54. }
  55. ///////////////////////////////////
  56. public class ClientInitializer extends ChannelInitializer {
  57. @Override
  58. protected void initChannel(Channel ch) throws Exception {
  59. ChannelPipeline p = ch.pipeline();
  60. p.addLast("decoder", new InputDecoder());
  61. p.addLast("encoder", new OutputEncoder());
  62. p.addLast("handler", new ClientHandler());
  63. p.addLast("httpExceptionHandler", new ClientExceptionHandler());
  64. }
  65. }
  66. ///////////////////////////////////
  67. public class ClientHandler extends SimpleChannelInboundHandler<String> {
  68. @Override
  69. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  70. System.out.println(msg);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement