Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
“快速”和“简单”并不用产生维护性或性能上的问题。Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性。
--百度百科
一,包引入
无论什么模块,第一步都是maven包引入,有很多种jar包,我们用 netty-all
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
二,服务端
2.1 因为用的线程启动的netty,所以我们在启动类启动:
@Autowired
private NettyServer nettyServer;
@Bean
public void run() throws Exception {
InetSocketAddress address = new InetSocketAddress(DefaultConstants.SOCKET_IP, DefaultConstants.SOCKET_PORT);
log.info("netty服务器启动地址: {}", DefaultConstants.SOCKET_IP);
nettyServer.start(address);
}
2.2 然后我们写 nettyServer.java
package com.julinkiot.ThreeFactory.netty.service;
import com.julinkiot.ThreeFactory.netty.client.NettyServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
/**
* @ClassName DiscardServer
*