netty3入门案例(代码片段)

_oldzhang _oldzhang     2022-12-06     719

关键词:

Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络服务器和客户端程序。也就是说它是一个NIO框架,使用它可以简单快速地开发网络应用程序。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。学习netty前需要对NIO理解得很透彻,可参考我另一篇文章java NIO或者网上找资料学习一下。

下面分别以类似HelloWorld的最基础案例来学习,案例是基于网络通信的。所以有Server端和Client端,当然客户端可以在本地使用telnet命令来测试。netty3和netty5版本在API上区别较大,下面是Netty3的一个例子。

Netty3 Server:

public class Server 
	public static void main(String[] args) 
		// 服务类,用于启动netty 在netty5中同样使用这个类来启动
		ServerBootstrap bootstrap = new ServerBootstrap();
		// 新建两个线程池  boss线程监听端口,worker线程负责数据读写
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		// 设置niosocket工厂  类似NIO程序新建ServerSocketChannel和SocketChannel
		bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));
		// 设置管道的工厂
		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("helloHandler", new HelloHandler());  //添加一个Handler来处理客户端的事件,Handler需要继承ChannelHandler
				return pipeline;
			
		);
		bootstrap.bind(new InetSocketAddress(10101));
		System.out.println("start!!!");
	
HelloHandler类:

public class HelloHandler extends SimpleChannelHandler 
	/** 接收消息*/
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception 
		String s = (String) e.getMessage();
		System.out.println(s);
		//回写数据
		ctx.getChannel().write("HelloWorld");
		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 channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelConnected");
		super.channelConnected(ctx, e);
	
	/** 必须是链接已经建立,关闭通道的时候才会触发  */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelDisconnected");
		super.channelDisconnected(ctx, e);
	
	/** channel关闭的时候触发 */
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelClosed");
		super.channelClosed(ctx, e);
	
到这里就可以启动Server端了。

netty3 Client:

public class Client 
	public static void main(String[] args) 
		// 客户端的启动类
		ClientBootstrap bootstrap = new  ClientBootstrap();
		//线程池
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		//socket工厂
		bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));
		//管道工厂
		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("hiHandler", new HiHandler());
				return pipeline;
			
		);
		//连接服务端
		ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));
		Channel channel = connect.getChannel();
		System.out.println("client start");
		Scanner scanner = new Scanner(System.in);
		while(true)
			System.out.println("请输入");
			channel.write(scanner.next());
		
	
客户端不断等待终端输入并写入通道。服务端接收到新的输入后会获取到输入的信息。对服务端的回写客户端也需要一个Handler来处理。下面是这客户端HiHandler的代码

public class HiHandler extends SimpleChannelHandler 
	/** 接收消息*/
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception 
		String s = (String) e.getMessage();
		System.out.println(s);
		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 channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelConnected");
		super.channelConnected(ctx, e);
	
	/** 必须是链接已经建立,关闭通道的时候才会触发*/
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelDisconnected");
		super.channelDisconnected(ctx, e);
	
	/** channel关闭的时候触发*/
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception 
		System.out.println("channelClosed");
		super.channelClosed(ctx, e);
	
至此就完成了Netty3的一个最基础的例子。

[mybatisplus]入门案例(代码片段)

入门案例创建测试数据库和表CREATEDATABASE`mybatis_plus`/*!40100DEFAULTCHARACTERSETutf8mb4*/;use`mybatis_plus`;CREATETABLE`user`(`id`bigint(20)NOTNULLCOMMENT'主键ID',`name&# 查看详情

intellijideamybatis入门案例(代码片段)

最近打算学习ssm框架 Mybatis作为入门的第一个持久层框架,学习起来实在费劲。故写此文章作为入门案例。先打开IDEA建立一个Maven项目,目录结构如下:源代码已经上传至GitHub https://github.com/Wo-com/mybatis_demo,需要的点击下... 查看详情

mybatis入门(开发环境+入门案例)(代码片段)

Mybatis入门1.MyBatis入门1.1概述2下载3与JDBC对比4入门:搭建环境4.1构建项目4.2数据库和表:User5入门案例:查询所有5.1JavaBean:User5.2编写Dao:UserMapper5.3编写核心配置文件:SqlMapConfig.xml5.4测试类6总结1.MyBatis入... 查看详情

实操案例入手讲解cmake的常见用法。(代码片段)

CMake的入门简单教程什么是CMake入门案例一:单个源文件1、编写源文件2、编写CMakeLists.txt3、编译项目入门案例二:多个源文件入门案例三:多个目录,多个源文件入门案例四:自定义编译选项入门案例五:... 查看详情

servlet入门案例(代码片段)

一、需求:登陆页面,查询数据库是否有此人,并统计登陆的次数、显示成功登陆与否信息1、登陆页面和登陆成功页面login.jsp:======================><%@pagelanguage="java"contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPEhtmlPUBL... 查看详情

完成springmvc的入门案例(代码片段)

...SpringMVC:理解SpringMVC相关概念今日内容完成SpringMVC的入门案例SpringMVC入门案例因为SpringMVC是一个Web框架,将来是要替换Servlet,所以先来回顾下以前Servlet是如何进行开发的?1.创建web工程(Maven结构)2.设置tomcat服务器,加载 查看详情

rabbitmq官方入门案例(代码片段)

官方提供7个案例RabbitMQ官方链接每个案例点击进去都会有详细讲解helloworld-demo导入依赖导入依赖<!--RabbitMQ依赖--><dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><versio 查看详情

scrapy框架-----入门案例(代码片段)

入门案例学习目标创建一个Scrapy项目定义提取的结构化数据(Item)编写爬取网站的Spider并提取出结构化数据(Item)编写ItemPipelines来存储提取到的Item(即结构化数据)一.新建项目(scrapystartproject)在开始爬取之前,必须创建一个新的Scrapy... 查看详情

springsecurity入门案例(代码片段)

1、搭建一个springboot项目2、导入相应jar包Maven坐标 完整pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http:/ 查看详情

vue学习:入门案例(代码片段)

开始前的准备IDE:VSCode(推荐)或者SublimeText前导技术:JavaScript中级案例页面代码:<divid="app"><ul><liv-for="productinproducts"><inputtype="number"v-model.number="produc 查看详情

springboot入门案例(代码片段)

一、引入依赖1.springboot项目必须继承springboot父工程<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-parent</artifactId><version>1.5.9.RELEASE</versio 查看详情

springsecurity简介及其入门案例(代码片段)

...现原理验证和授权的过程及本质主要过滤器核心组件简介入门案例引入依赖好,入门了,牛了你就SpringSecurity概念官网介绍:https://spring.io/projects/spring-security/SpringSecurity是一个能够为基于Spring的企业应用系统提供声明... 查看详情

spring入门案例(简单)(代码片段)

Spring的入门案例(简单)该案例主要用来概述使用SpringIOC方式创建对象并调用方法,希望对大家有所帮助Spring的概述什么是Spring:Spring是分层的JavaSE/EE应用full-stack轻量级开源框架Spring的两大核心:IOC(InverseOfCon... 查看详情

首个springmvc入门案例报错(代码片段)

HTTPStatus500–InternalServerErrorType 异常报告消息 Servlet.init()forservlet[dispatcherServlet]threwexception描述 服务器遇到一个意外的情况,阻止它完成请求。Exceptionjavax.servlet.ServletException:Servlet.init( 查看详情

vue入门案例(代码片段)

...>2<html>3<head>4<metacharset="UTF-8">5<title>vue入门</title>6<!--引入vue.min.js文件,直接引用这个文件就行了 查看详情

1mybatis入门案例(代码片段)

1环境搭建第一步:创建maven工程并导入坐标 第二步:创建实体类和dao的接口 第三步:创建Mybatis的主配置文件     SqlMapConifg.xml 第四步:创建映射配置文件     IUserDao.xml2 环境搭建的注意事项第一个:创建IUse... 查看详情

aop入门案例-基于xml(代码片段)

  <?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.o 查看详情

字节码javaagent入门案例最简单的案例(代码片段)

1.概述JavaAgent是在JDK5之后提供的新特性,也可以叫java代理。开发者通过这种机制(Instrumentation)可以在加载class文件之前修改方法的字节码(此时字节码尚未加入JVM),动态更改类方法实现AOP,提供监控服务如;方法调用时长、可用... 查看详情