• zbb20180917 nio,netty5服务器端客户端例子


    Netty服务器

    class ServerHandler extends SimpleChannelHandler {

    /**

     * 通道关闭的时候触发

     */

    @Override

    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    System.out.println("channelClosed");

    }

    /**

     * 必须是连接已经建立,关闭通道的时候才会触发.

     */

    @Override

    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    super.channelDisconnected(ctx, e);

    System.out.println("channelDisconnected");

    }

    /**

     * 捕获异常

     */

    @Override

    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {

    super.exceptionCaught(ctx, e);

    System.out.println("exceptionCaught");

    }

    /**

     * 接受消息

     */

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    super.messageReceived(ctx, e);

    // System.out.println("messageReceived");

    System.out.println("服务器端收到客户端消息:"+e.getMessage());

    //回复内容

    ctx.getChannel().write("好的");

    }

    }

    // netty 服务器端

    public class NettyServer {

    public static void main(String[] args) {

    // 创建服务类对象

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    // 创建两个线程池 分别为监听监听端口 ,nio监听

    ExecutorService boos = Executors.newCachedThreadPool();

    ExecutorService worker = Executors.newCachedThreadPool();

    // 设置工程 并把两个线程池加入中

    serverBootstrap.setFactory(new NioServerSocketChannelFactory(boos, worker));

    // 设置管道工厂

    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

    public ChannelPipeline getPipeline() throws Exception {

    ChannelPipeline pipeline = Channels.pipeline();

    //将数据转换为string类型.

    pipeline.addLast("decoder", new StringDecoder());

    pipeline.addLast("encoder", new StringEncoder());

    pipeline.addLast("serverHandler", new ServerHandler());

    return pipeline;

    }

    });

    // 绑定端口号

    serverBootstrap.bind(new InetSocketAddress(9090));

    System.out.println("netty server启动....");

    }

    }

    Netty客户端

    package com.itmayiedu;

    import java.net.InetSocketAddress;

    import java.util.Scanner;

    import java.util.concurrent.ExecutorService;

    import java.util.concurrent.Executors;

    import org.jboss.netty.bootstrap.ClientBootstrap;

    import org.jboss.netty.channel.Channel;

    import org.jboss.netty.channel.ChannelFuture;

    import org.jboss.netty.channel.ChannelHandlerContext;

    import org.jboss.netty.channel.ChannelPipeline;

    import org.jboss.netty.channel.ChannelPipelineFactory;

    import org.jboss.netty.channel.ChannelStateEvent;

    import org.jboss.netty.channel.Channels;

    import org.jboss.netty.channel.ExceptionEvent;

    import org.jboss.netty.channel.MessageEvent;

    import org.jboss.netty.channel.SimpleChannelHandler;

    import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

    import org.jboss.netty.handler.codec.string.StringDecoder;

    import org.jboss.netty.handler.codec.string.StringEncoder;

    class ClientHandler extends SimpleChannelHandler {

    /**

     * 通道关闭的时候触发

     */

    @Override

    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    System.out.println("channelClosed");

    }

    /**

     * 必须是连接已经建立,关闭通道的时候才会触发.

     */

    @Override

    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    super.channelDisconnected(ctx, e);

    System.out.println("channelDisconnected");

    }

    /**

     * 捕获异常

     */

    @Override

    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {

    super.exceptionCaught(ctx, e);

    System.out.println("exceptionCaught");

    }

    /**

     * 接受消息

     */

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    super.messageReceived(ctx, e);

    // System.out.println("messageReceived");

    System.out.println("服务器端向客户端回复内容:"+e.getMessage());

    //回复内容

    // ctx.getChannel().write("好的");

    }

    }

    public class NettyClient {

    public static void main(String[] args) {

    System.out.println("netty client启动...");

    // 创建客户端类

    ClientBootstrap clientBootstrap = new ClientBootstrap();

    // 线程池

    ExecutorService boos = Executors.newCachedThreadPool();

    ExecutorService worker = Executors.newCachedThreadPool();

    clientBootstrap.setFactory(new NioClientSocketChannelFactory(boos, worker));

    clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

    public ChannelPipeline getPipeline() throws Exception {

    ChannelPipeline pipeline = Channels.pipeline();

    // 将数据转换为string类型.

    pipeline.addLast("decoder", new StringDecoder());

    pipeline.addLast("encoder", new StringEncoder());

    pipeline.addLast("clientHandler", new ClientHandler());

    return pipeline;

    }

    });

    //连接服务端

    ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 9090));

    Channel channel = connect.getChannel();

    System.out.println("client start");

    Scanner scanner= new Scanner(System.in);

    while (true) {

    System.out.println("请输输入内容...");

    channel.write(scanner.next());

    }

    }

    }

    Maven坐标

    <dependency>

    <groupId>io.netty</groupId>

    <artifactId>netty</artifactId>

    <version>3.3.0.Final</version>

    </dependency>

     

    Netty5.0用法

    创建服务器

    class ServerHandler extends ChannelHandlerAdapter {

    /**

     * 当通道被调用,执行该方法

     */

    @Override

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    // 接收数据

    String value = (String) msg;

    System.out.println("Server msg:" + value);

    // 回复给客户端 “您好!”

    String res = "好的...";

    ctx.writeAndFlush(Unpooled.copiedBuffer(res.getBytes()));

    }

     

    }

     

    public class NettyServer {

     

    public static void main(String[] args) throws InterruptedException {

    System.out.println("服务器端已经启动....");

    // 1.创建2个线程,一个负责接收客户端连接, 一个负责进行 传输数据

    NioEventLoopGroup pGroup = new NioEventLoopGroup();

    NioEventLoopGroup cGroup = new NioEventLoopGroup();

    // 2. 创建服务器辅助类

    ServerBootstrap b = new ServerBootstrap();

    b.group(pGroup, cGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)

    // 3.设置缓冲区与发送区大小

    .option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)

    .childHandler(new ChannelInitializer<SocketChannel>() {

    @Override

    protected void initChannel(SocketChannel sc) throws Exception {

    sc.pipeline().addLast(new StringDecoder());

    sc.pipeline().addLast(new ServerHandler());

    }

    });

    ChannelFuture cf = b.bind(8080).sync();

    cf.channel().closeFuture().sync();

    pGroup.shutdownGracefully();

    cGroup.shutdownGracefully();

    }

     

    }

     

    创建客户端

    class ClientHandler extends ChannelHandlerAdapter {

     

    /**

     * 当通道被调用,执行该方法

     */

    @Override

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    // 接收数据

    String value = (String) msg;

    System.out.println("client msg:" + value);

    }

     

    }

     

    public class NettyClient {

     

    public static void main(String[] args) throws InterruptedException {

    System.out.println("客户端已经启动....");

    // 创建负责接收客户端连接

    NioEventLoopGroup pGroup = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();

    b.group(pGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

    @Override

    protected void initChannel(SocketChannel sc) throws Exception {

    sc.pipeline().addLast(new StringDecoder());

    sc.pipeline().addLast(new ClientHandler());

    }

    });

    ChannelFuture cf = b.connect("127.0.0.1", 8080).sync();

     cf.channel().writeAndFlush(Unpooled.wrappedBuffer("itmayiedu".getBytes()));

     cf.channel().writeAndFlush(Unpooled.wrappedBuffer("itmayiedu".getBytes()));

    // 等待客户端端口号关闭

    cf.channel().closeFuture().sync();

    pGroup.shutdownGracefully();

     

    }

     

    }

    Maven坐标

    <dependencies>

    <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->

    <dependency>

    <groupId>io.netty</groupId>

    <artifactId>netty-all</artifactId>

    <version>5.0.0.Alpha2</version>

    </dependency>

     

    <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling -->

    <dependency>

    <groupId>org.jboss.marshalling</groupId>

    <artifactId>jboss-marshalling</artifactId>

    <version>1.3.19.GA</version>

    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-serial -->

    <dependency>

    <groupId>org.jboss.marshalling</groupId>

    <artifactId>jboss-marshalling-serial</artifactId>

    <version>1.3.18.GA</version>

    <scope>test</scope>

    </dependency>

     

    </dependencies>

  • 相关阅读:
    UiAutomator自动化测试框架介绍
    mongkeyrunner实现循环随机输入值的方法
    python出输出字符串方式:
    Python之字符串小代码解析
    安装JDK,Python SDK及环境变量的配置
    Monkeyrunner小脚本关于camera的使用
    ubuntu 下安装32位库 ia32-libs方法
    关于monkeyrunner的一些初步理解性的题目
    基于redis的限流
    表单防重复提交
  • 原文地址:https://www.cnblogs.com/super-admin/p/9662860.html
Copyright © 2020-2023  润新知