Netty 简单的通信

1.创建Maven项目

2.pom.xml的引入

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty</artifactId>
    <version>3.10.6.Final</version>
</dependency>

 3.服务端代码

package com.example.demo.netty;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: demo
 * @description:
 * @author: Gaojq
 * @create: 2021-07-30 08:55
 **/
public class NettyServer {

    public static void main(String[] args) {
        // 1.创建服务对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 2.创建两个线程池 监听端口和NIO监听
        ExecutorService bossExecutor = Executors.newCachedThreadPool();// 监听端口
        ExecutorService workerExecutor = Executors.newCachedThreadPool();// NIO监听

        // 3.将线程池放入工厂 此处是NioServerSocketChannelFactory方法 客户端不同
        bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor,workerExecutor));

        // 4.设置管道工程
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder",new StringDecoder());
                pipeline.addLast("encoder",new StringEncoder());
                pipeline.addLast("serverHandler", new ServerHandler());
                return pipeline;
            }
        });

        bootstrap.bind(new InetSocketAddress(8080));
        System.out.println("netty 服务端启动成功~");

    }

}

/**
 *
 */
class ServerHandler extends SimpleChannelHandler{

    // 接收 客户端数据
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        System.out.println("messageReceived~服务端接收到客户端的消息:"+e.getMessage());
        Channel channel = ctx.getChannel();
        channel.write("你好啊");// 返回客户端消息
    }


    // 接收出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("exceptionCaught");
    }

    // 必须要建立连接 关闭通道的时候才会触发
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("channelDisconnected");
    }

    // 通道关闭的时候才会触发
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
        System.out.println("channelClosed");
    }
}

4.客户端代码

package com.example.demo.netty;

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.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: demo
 * @description:
 * @author: Gaojq
 * @create: 2021-07-30 08:55
 **/
public class NettyClient {

    public static void main(String[] args) {
        ClientBootstrap clientBootstrap = new ClientBootstrap();

        ExecutorService bossExecutor = Executors.newCachedThreadPool();
        ExecutorService workExecutor = Executors.newCachedThreadPool();
      clientBootstrap.setFactory(
new NioClientSocketChannelFactory(bossExecutor,workExecutor)); clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline channelPipeline = Channels.pipeline(); channelPipeline.addLast("decoder",new StringDecoder()); channelPipeline.addLast("encoder",new StringEncoder()); channelPipeline.addLast("clientHandler", new ClientHandler()); return channelPipeline; } }); ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)); Channel channel = connect.getChannel(); channel.write("nice");// 向服务器发送消息 } } class ClientHandler extends SimpleChannelHandler{ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.messageReceived(ctx, e); System.out.println("messageReceived~客户端接收到服务端返回的消息:"+e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { super.exceptionCaught(ctx, e); System.out.println("exceptionCaught"); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { super.channelDisconnected(ctx, e); System.out.println("channelDisconnected"); } @Override public void childChannelClosed(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { super.childChannelClosed(ctx, e); System.out.println("childChannelClosed"); } }

 5.客户端与服务端主要的区别就是:

  • 创建的服务不同 客户端是 ClientBootstrap ,而服务器创建的服务是 ServerBootstrap 
  • 第三步 对工程的设置不同 客户端是clientBootstrap.setFactory(new NioClientSocketChannelFactory,服务端为bootstrap.setFactory(new NioServerSocketChannelFactory 
  • 配置管道的处理服务不同  客户端是channelPipeline.addLast("clientHandler", new ClientHandler());,服务端为  pipeline.addLast("serverHandler", new ServerHandler()); 
  • 最后就是建立socket的部分 客户端是 clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));,服务端为  bootstrap.bind(new InetSocketAddress(8080)); 

 

posted @ 2021-07-30 10:36  An-Optimistic-Person  阅读(94)  评论(0编辑  收藏  举报