• Netty学习一 HelloWorld


    1、netty服务端开发套路

    > 1、创建线程组,指定负责连接客户端的通道 > 2、初始化通道,该类继承ChannelInitializer类,并指定各种Handler > 3、添加自定义Handler,需要继承ChannelInboundHandlerAdapter

    2、maven依赖

    ``` io.netty netty-all 4.1.6.Final ```

    3、服务端

    入口

    public class HelloWorldServer {
    	
    	private int port;
    	
    	public HelloWorldServer(int port) {
    		this.port = port;
    	}
    	
    	public void start(){
    		EventLoopGroup bossGroup = new NioEventLoopGroup();//创建父子线程组
    		EventLoopGroup workGroup = new NioEventLoopGroup();
    		
    		ServerBootstrap server = new ServerBootstrap();
    		server.group(bossGroup, workGroup)
    			  .channel(NioServerSocketChannel.class)//指定处理客户端的通道
    			  .childHandler(new ServerChannelInitializer());//通道初始化
    		
    		try {
    			ChannelFuture future = server.bind(port).sync();
    			future.channel().closeFuture().sync();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		} finally{
    			bossGroup.shutdownGracefully();
    			workGroup.shutdownGracefully();
    		}
    	}
    
    	public static void main(String[] args) {
    		HelloWorldServer server = new HelloWorldServer(8888);
    		server.start();
    	}
    
    }
    

    通道初始化

    public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    
    	@Override
    	protected void initChannel(SocketChannel socketChannel) throws Exception {
    		ChannelPipeline pipeline = socketChannel.pipeline();
    		pipeline.addLast("decoder", new StringDecoder());// 字符串解码和编码
    		pipeline.addLast("encoder", new StringEncoder());
    		pipeline.addLast("handler", new HelloWordServerHandler());//自定义handler
    	}
    
    }
    

    自定义处理器

    public class HelloWordServerHandler extends ChannelInboundHandlerAdapter {
    
    	@Override
    	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    		System.out.println("服务端收到消息:[" + msg + "]");
    		ctx.writeAndFlush("欢迎你,客户端");
    	}
    
    }
    
    

    4、客户端

    ### 入口 ``` public class HelloWorldClient {
    private int port;
    private String address;
    
    public HelloWorldClient(int port, String address) {
    	this.port = port;
    	this.address = address;
    }
    
    public void start() {
    	EventLoopGroup group = new NioEventLoopGroup();
    
    	Bootstrap bootstrap = new Bootstrap();
    	bootstrap.group(group).channel(NioSocketChannel.class)
    			.handler(new ClientChannelInitializer());
    
    	try {
    		ChannelFuture future = bootstrap.connect(address,port).sync();
    		Channel channel = future.channel();
    		channel.writeAndFlush("我是客户端,地址:" + channel.remoteAddress());
    		channel.closeFuture().sync();
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		group.shutdownGracefully();
    	}
    }
    
    public static void main(String[] args) {
    	HelloWorldClient client = new HelloWorldClient(8888, "127.0.0.1");
    	client.start();
    }
    

    }

    ### 通道初始化
    

    public class ClientChannelInitializer extends ChannelInitializer {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
    	ChannelPipeline pipeline = socketChannel.pipeline();
    
    	pipeline.addLast("decoder", new StringDecoder());//字符串解码和编码
    	pipeline.addLast("encoder", new StringEncoder());
    	pipeline.addLast("handler", new HelloWorldClientHandler());//自定义handler
    }
    

    }

    ### 自定义处理器
    

    public class HelloWorldClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	System.out.println("客户端收到消息:[" + msg + "]");
    }
    

    }

    
    <h1>5、运行</h1>
    先启动服务端,再启动客户端,可以看到,服务端和客户端分别收到了对方发送的消息
    ### 服务端收到消息
    ![](https://img2018.cnblogs.com/blog/1373276/201906/1373276-20190603163957020-260958172.png)
    ### 客户端收到消息
    ![](https://img2018.cnblogs.com/blog/1373276/201906/1373276-20190603164006441-471814764.png)
  • 相关阅读:
    用Python写春联:抒写最真诚的祝福和最美好的祈愿
    python 注册表操作
    python 多参数
    arcgis tin版本转换使用复制tin
    python基础知识
    模型免费学习地址https://space.bilibili.com/378493128?spm_id_from=333.788
    在Python中用turtle函数画同心圆
    solr系统query检索词特殊字符的处理
    C#winform抓取百度,Google搜索关键词结果
    理解Solr缓存及如何设置缓存大小
  • 原文地址:https://www.cnblogs.com/lmj612/p/10845725.html
Copyright © 2020-2023  润新知