博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Netty3- 入门示例
阅读量:4041 次
发布时间:2019-05-24

本文共 7105 字,大约阅读时间需要 23 分钟。

Netty 版本: netty 3.x

1.服务端入门示例 - HelloServer

 

package xss.netty.netty3;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.jboss.netty.handler.codec.string.StringDecoder;import java.net.InetSocketAddress;import java.util.concurrent.Executor;import java.util.concurrent.Executors;/** * netty 3 的入门示例 - 服务端 */public class HelloServer {    public static void main(String[] args) throws  Exception {        //服务启动类        ServerBootstrap bootstrap=new ServerBootstrap();        //两个工作线程池        Executor bossExecutor = Executors.newCachedThreadPool();//boss 线程池工作组        Executor workerExecutor=Executors.newCachedThreadPool();//work线程池工作组        //设置factory        bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor,workerExecutor));        //设置管道过滤器工厂        bootstrap.setPipelineFactory(new ChannelPipelineFactory(){            public ChannelPipeline getPipeline() throws Exception {                //pipe 类型分为上行与下行                ChannelPipeline channelPipeline= Channels.pipeline();                //将输出参数转换为String对象输出到下一个pipe                channelPipeline.addLast("decorder",new StringDecoder());                //业务处理的过滤器类                channelPipeline.addLast("helloHandler",new HelloServerHandler());                return channelPipeline;            }        });        //绑定端口        bootstrap.bind(new InetSocketAddress(9999));        System.out.println("Server started...");    }}

对应的请求处理类:HelloServerHandler

package xss.netty.netty3;import org.jboss.netty.channel.*;/** * 连接 *  channelOpen->channelConnected *                  ->messageReceived *        -> channelDisconnected->channelClosed */public class HelloServerHandler extends SimpleChannelHandler {    @Override    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {        System.out.println("messageReceived "+e.getMessage());        //1.在没有前置自动类型转换的情况下//        ChannelBuffer channelBuffer=(ChannelBuffer)e.getMessage();//        System.out.println("message from client="+new String(channelBuffer.array()));        //2. channelPipeline.addLast("stringDec",new StringDecoder()); 的情况下        System.out.println("message from client="+(String)e.getMessage());        super.messageReceived(ctx, e);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {        System.out.println("exceptionCaught");        super.exceptionCaught(ctx, e);    }    @Override    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelOpen");        super.channelOpen(ctx, e);    }    @Override    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelConnected");        super.channelConnected(ctx, e);    }    @Override    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelClosed");        super.channelClosed(ctx, e);    }    @Override    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelDisconnected");        super.channelDisconnected(ctx, e);    }}

2.客户端 - HelloClient

package xss.netty.netty3;import org.jboss.netty.bootstrap.ClientBootstrap;import org.jboss.netty.channel.*;import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;import org.jboss.netty.handler.codec.string.StringDecoder;import org.jboss.netty.handler.codec.string.StringEncoder;import java.net.InetSocketAddress;import java.util.Scanner;import java.util.concurrent.Executor;import java.util.concurrent.Executors;/** *Netty 3 的客户端示例 */public class HelloClient {    public static void main(String[] args) throws Exception{        //客户端的服务类        ClientBootstrap clientBootstrap=new ClientBootstrap();        java.util.concurrent.Executor bossExecutor=Executors.newCachedThreadPool();        Executor workerExecutor= Executors.newCachedThreadPool();        clientBootstrap.setFactory(new NioClientSocketChannelFactory(bossExecutor,workerExecutor));        //设置pipeline factory        clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {            public ChannelPipeline getPipeline() throws Exception {                ChannelPipeline channelPipeline=Channels.pipeline();                channelPipeline.addLast("decoder",new StringDecoder());                channelPipeline.addLast("encoder",new StringEncoder());                channelPipeline.addLast("hello",new HelloClientHandler());                return channelPipeline;            }        });        //连接服务端        ChannelFuture channelFuture = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 9999));        Channel channel = channelFuture.getChannel();        System.out.println("client connect to server");        Scanner scanner=new Scanner(System.in);        while (true){            System.out.println("input:");            channel.write(scanner.next());        }    }}

 

package xss.netty.netty3;import org.jboss.netty.channel.*;/** * 连接 *  channelOpen->channelConnected *                  ->messageReceived *        -> channelDisconnected->channelClosed */public class HelloClientHandler extends SimpleChannelHandler {    @Override    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {        System.out.println("messageReceived "+e.getMessage());        //1.在没有前置自动类型转换的情况下//        ChannelBuffer channelBuffer=(ChannelBuffer)e.getMessage();//        System.out.println("message from client="+new String(channelBuffer.array()));        //2. channelPipeline.addLast("stringDec",new StringDecoder()); 的情况下        System.out.println("message from client="+(String)e.getMessage());        super.messageReceived(ctx, e);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {        System.out.println("exceptionCaught");        super.exceptionCaught(ctx, e);    }    @Override    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelOpen");        super.channelOpen(ctx, e);    }    @Override    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelConnected");        super.channelConnected(ctx, e);    }    @Override    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelClosed");        super.channelClosed(ctx, e);    }    @Override    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {        System.out.println("channelDisconnected");        super.channelDisconnected(ctx, e);    }}

 

3.总结:

业务逻辑根据业务继承:org.jboss.netty.channel.SimpleChannelHandler ,这样就无需太多的关心Socker连接的处理。

 

 

 

转载地址:http://bwadi.baihongyu.com/

你可能感兴趣的文章
使用Navicat计划任务备份mysql数据库
查看>>
Java高并发,如何解决,什么方式解决
查看>>
深入理解分布式事务,高并发下分布式事务的解决方案
查看>>
分布式事务一些总结与思考
查看>>
Spring Cloud微服务架构实践与经验总结
查看>>
Spring Boot入门篇
查看>>
spring cloud服务的注册与发现(Eureka)
查看>>
Java IO流
查看>>
多线程
查看>>
互联网产品设计:产品即服务
查看>>
UrlreWirte的使用
查看>>
使用js定位到页面某个位子
查看>>
java获取客户端真实ip
查看>>
SWFUPLOAD的使用(java版)
查看>>
Memcached的使用(基于java)
查看>>
java ee中的乱码问题及解决方案
查看>>
从技术到管理:思维转变是关键
查看>>
spring2.5.6下配置定时器
查看>>
为什么很多程序员都选择跳槽?
查看>>
mongdb介绍
查看>>