首先值得注意的是netty的jar包版本问题,版本不同,运用的方式也不同。我这里用4.0版本。

  对于小白来说,netty到底是什么,我就没必要在这里阐明了,因为百度上比我描述的更全面。

  这里就直接开门见山,代码走起。。。

 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioServerSocketChannel;

 /**
  * 服务器
  */
 public class NettyServer {
     private final int port = 8989;

     public static void main(String[] args) {
         new NettyServer().nettyServer();
     }

     public void nettyServer(){
         EventLoopGroup bossGroup = new NioEventLoopGroup();
         EventLoopGroup workerGroup = new NioEventLoopGroup();

         try {
             ServerBootstrap serverBootStrap = new ServerBootstrap();

             serverBootStrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 1024)
             .childHandler(new ChildChannelHandler());

             ChannelFuture futrue = serverBootStrap.bind(port).sync();
             futrue.channel().closeFuture().sync();

         } catch (Exception e) {
             // TODO: handle exception
         }
     }

     private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

         @Override
         protected void initChannel(SocketChannel ch) throws Exception {
             ch.pipeline().addLast(new SimpleServerHandler());
         }

     }
 }
 import java.util.Scanner;

 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;

 public class SimpleServerHandler extends ChannelInboundHandlerAdapter {

     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {

         ChannelManager.serverChannel = ctx;

         new Thread(new Runnable() {

             @Override
             public void run() {
                 // TODO Auto-generated method stub
                 while(true){

                     Scanner sc = new Scanner(System.in);
                     byte [] req = sc.nextLine().getBytes();
                     ByteBuf msg = Unpooled.buffer(req.length);
                     msg.writeBytes(req);
                     ChannelManager.serverChannel.writeAndFlush(msg);
                 }
             }
         }).start();
     }

     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg)
             throws Exception {
         ByteBuf buf = (ByteBuf) msg;
         byte [] req = new byte[buf.readableBytes()];

         buf.readBytes(req);
         String message = new String(req,"UTF-8");
         System.out.println("server:"+message);
     }

 }

  上述两个类实现netty的服务端,下面就是客户端啦

 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;

 public class NettyClient {

     public static void main(String[] args) {
         new NettyClient().connect(8989, "127.0.0.1");
     }

     public void connect(int port, String host){
         EventLoopGroup  group = new NioEventLoopGroup();

         try {
             Bootstrap bootstrap = new Bootstrap();
             bootstrap.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(new ChannelInitializer<SocketChannel>() {

                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     // TODO Auto-generated method stub
                     ch.pipeline().addLast(new SimpleClientHandler());
                 }

             });
             ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
             channelFuture.channel().closeFuture().sync();

         } catch (Exception e) {
             // TODO: handle exception
         }
     }
 }
 import java.util.Scanner;

 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;

 public class SimpleClientHandler extends ChannelInboundHandlerAdapter {

     private ByteBuf clientMessage;

     public SimpleClientHandler(){
         byte [] req = "call-user-service".getBytes();
         clientMessage = Unpooled.buffer(req.length);
         clientMessage.writeBytes(req);
     }

     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {

         ChannelManager.clientChannel = ctx;

         new Thread(new Runnable() {

             @Override
             public void run() {
                 // TODO Auto-generated method stub
                 while(true){

                     Scanner sc = new Scanner(System.in);
                     byte [] req = sc.nextLine().getBytes();
                     ByteBuf msg = Unpooled.buffer(req.length);
                     msg.writeBytes(req);
                     ChannelManager.clientChannel.writeAndFlush(msg);
                 }
             }
         }).start();
     }

     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg)
             throws Exception {
         ByteBuf buf = (ByteBuf) msg;
         byte [] req = new byte[buf.readableBytes()];
         buf.readBytes(req);

         String message = new String(req,"UTF-8");
         System.out.println("client:"+message);
     }

     @Override
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
             throws Exception {
         ctx.close();
     }

 }

  好了,万事俱备,再添加一个ChannelManager.java netty的通道管理器

 import io.netty.channel.ChannelHandlerContext;

 public class ChannelManager {

     public static ChannelHandlerContext serverChannel;
     public static ChannelHandlerContext clientChannel;
 }

这样就可以实现netty的前后端的控制台通讯了,代码解释就不进行了

Netty的更多相关文章

  1. 谈谈如何使用Netty开发实现高性能的RPC服务器

    RPC(Remote Procedure Call Protocol)远程过程调用协议,它是一种通过网络,从远程计算机程序上请求服务,而不必了解底层网络技术的协议.说的再直白一点,就是客户端在不必知道 ...

  2. 基于netty http协议栈的轻量级流程控制组件的实现

    今儿个是冬至,所谓“冬大过年”,公司也应景五点钟就放大伙儿回家吃饺子喝羊肉汤了,而我本着极高的职业素养依然坚持留在公司(实则因为没饺子吃没羊肉汤喝,只能呆公司吃食堂……).趁着这一个多小时的时间,想跟 ...

  3. 从netty-example分析Netty组件续

    上文我们从netty-example的Discard服务器端示例分析了netty的组件,今天我们从另一个简单的示例Echo客户端分析一下上个示例中没有出现的netty组件. 1. 服务端的连接处理,读 ...

  4. 源码分析netty服务器创建过程vs java nio服务器创建

    1.Java NIO服务端创建 首先,我们通过一个时序图来看下如何创建一个NIO服务端并启动监听,接收多个客户端的连接,进行消息的异步读写. 示例代码(参考文献[2]): import java.io ...

  5. 从netty-example分析Netty组件

    分析netty从源码开始 准备工作: 1.下载源代码:https://github.com/netty/netty.git 我下载的版本为4.1 2. eclipse导入maven工程. netty提 ...

  6. Netty实现高性能RPC服务器优化篇之消息序列化

    在本人写的前一篇文章中,谈及有关如何利用Netty开发实现,高性能RPC服务器的一些设计思路.设计原理,以及具体的实现方案(具体参见:谈谈如何使用Netty开发实现高性能的RPC服务器).在文章的最后 ...

  7. Netty构建分布式消息队列(AvatarMQ)设计指南之架构篇

    目前业界流行的分布式消息队列系统(或者可以叫做消息中间件)种类繁多,比如,基于Erlang的RabbitMQ.基于Java的ActiveMQ/Apache Kafka.基于C/C++的ZeroMQ等等 ...

  8. 基于Netty打造RPC服务器设计经验谈

    自从在园子里,发表了两篇如何基于Netty构建RPC服务器的文章:谈谈如何使用Netty开发实现高性能的RPC服务器.Netty实现高性能RPC服务器优化篇之消息序列化 之后,收到了很多同行.园友们热 ...

  9. Netty构建分布式消息队列实现原理浅析

    在本人的上一篇博客文章:Netty构建分布式消息队列(AvatarMQ)设计指南之架构篇 中,重点向大家介绍了AvatarMQ主要构成模块以及目前存在的优缺点.最后以一个生产者.消费者传递消息的例子, ...

  10. JAVA通信系列三:Netty入门总结

    一.Netty学习资料 书籍<Netty In Action中文版> 对于Netty的十一个疑问http://news.cnblogs.com/n/205413/ 深入浅出Nettyhtt ...

随机推荐

  1. android studio 各种问题

    1.dexDebug ExecException finished with non-zero exit value 2 全bug日志如下: (Error:Execution failed for t ...

  2. BFS与DFS

    DFS:使用栈保存未被检测的结点,结点按照深度优先的次序被访问并依次被压入栈中,并以相反的次序出栈进行新的检测. 类似于树的先根遍历深搜例子:走迷宫,你没有办法用分身术来站在每个走过的位置.不撞南山不 ...

  3. 拥抱高效、拥抱 Bugtags 之来自用户的声音(三)

    小编按:这是一篇 Bugtags 用户来稿,主要是介绍了使用 Bugtags 前后对测试及解决 Bug 所带来的变化,感谢山西农业大学 - 高正炎同学对 Bugtags 的信赖和支持.小编在这里诚邀各 ...

  4. SpringMVC实例分析

    Spring的MVC模块 Spring提供了自己的MVC框架实现,相比Struts.WebWork等MVC模块,Spring的MVC模块显得小巧而灵活.Spring的MVC使用Controller处理 ...

  5. logstash 配置 logstash-forwarder (前名称:lumberjack)

    logstash-forwarder(曾名lumberjack)是一个用go语言写的日志发送端, 主要是为一些机器性能不足,有性能强迫症的患者准备的. 主要功能: 通过配置的信任关系,把被监控机器的日 ...

  6. ThinkPHP3.2.3 跨域访问

    其他程序调用tp项目的action时需要进行跨域设置,在tp项目根目录下添加crossdomain.xml文件. 文件内容:  <?xml version="1.0"?> ...

  7. yii-basic-app-2.0.5/basic/config/web.php

    <?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => ...

  8. vim学习

    vim编辑器的工作模式分为3种 1.Command Mode 命令模式 2.Insert Mode 插入模式 3.Lastline Mode 底行模式 vim 打开文件时处于命令模式,i 可以切换到插 ...

  9. Use filter in outlook2013

    1. 条件与条件间用分号隔开 2. search带附件的邮件:hasattachments:yes

  10. 转载:最近有两款路由器D-link , Tenda分别被爆出固件中存在后门

    最近有两款路由器分别被爆出固件中存在后门. D-link D-link是台湾公司,成立于1986年,『公司致力于高级网络.宽带.数字.语音和数据通信解决方案的设计.制造和营销,是业界的全球领导者』(官 ...