# websocketWithNetty
**Repository Path**: flexspike/websocketWithNetty
## Basic Information
- **Project Name**: websocketWithNetty
- **Description**: 基于netty搭建websocket服务器
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2020-05-15
- **Last Updated**: 2021-06-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# websocketWithNetty
基于netty搭建websocket服务器
> netty是由jboss提供的一款开源框架,常用于搭建RPC中的TCP服务器、websocket服务器,甚至是类似tomcat的web服务器,反正就是各种网络服务器,在处理高并发的项目中,有奇用!功能丰富且性能良好,基于java中NIO的二次封装,具有比原生NIO更好更稳健的体验。
## netty的核心架构

官网给出的底层示意图:

## 1.项目结构

一个普通的maven项目即可
- 核心依赖:
```xml
io.netty
netty-all
4.1.6.Final
com.fasterxml.jackson.core
jackson-databind
2.9.7
log4j
log4j
1.2.17
```
## 代码
1.启动类
```java
public class NioWebSocketServer {
private final Logger logger=Logger.getLogger(this.getClass());
private void init(){
logger.info("正在启动websocket服务器");
NioEventLoopGroup boss=new NioEventLoopGroup();
NioEventLoopGroup work=new NioEventLoopGroup();
try {
ServerBootstrap bootstrap=new ServerBootstrap();
bootstrap.group(boss,work);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new NioWebSocketChannelInitializer());
Channel channel = bootstrap.bind(8081).sync().channel();
logger.info("webSocket服务器启动成功:"+channel);
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
logger.info("运行出错:"+e);
}finally {
boss.shutdownGracefully();
work.shutdownGracefully();
logger.info("websocket服务器已关闭");
}
}
public static void main(String[] args) {
new NioWebSocketServer().init();
}
}
```
netty搭建的服务器基本上都是差不多的写法:
- 绑定主线程组和工作线程组,这部分对应架构图中的事件循环组
- 只有服务器才需要绑定端口,客户端是绑定一个地址
- 配置channel(数据通道)参数,重点就是`ChannelInitializer`的配置
- 以异步的方式启动,最后是结束关闭两个线程组
2.ChannelInitializer写法
```java
public class NioWebSocketChannelInitializer extends ChannelInitializer {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast("logging",new LoggingHandler("DEBUG"));//设置log监听器,并且日志级别为debug,方便观察运行流程
ch.pipeline().addLast("http-codec",new HttpServerCodec());//设置解码器
ch.pipeline().addLast("aggregator",new HttpObjectAggregator(65536));//聚合器,使用websocket会用到
ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//用于大数据的分区传输
ch.pipeline().addLast("handler",new NioWebSocketHandler());//自定义的业务handler
}
}
```
3.自定义的处理器**NioWebSocketHandler**
```java
public class NioWebSocketHandler extends SimpleChannelInboundHandler