Commit 588ff4e9 by levphon

集成netty,支持websocket

1 parent c6638964
...@@ -58,6 +58,12 @@ ...@@ -58,6 +58,12 @@
<version>1.2.0-SNAPSHOT</version> <version>1.2.0-SNAPSHOT</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>ne-shield-auth-client</artifactId>
<version>1.2.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package cn.com.glsx; package cn.com.glsx;
import cn.com.glsx.notify.netty.CoordinationNettyServer; import cn.com.glsx.notify.netty.NettyServer;
import com.glsx.plat.context.EnableRestAdmin; import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
...@@ -35,7 +35,7 @@ public class Application { ...@@ -35,7 +35,7 @@ public class Application {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
//启动NettyServer服务端 //启动NettyServer服务端
new CoordinationNettyServer(9779).start(); new NettyServer(9779).start();
} }
@PostConstruct @PostConstruct
......
...@@ -8,6 +8,7 @@ import io.netty.handler.codec.http.HttpServerCodec; ...@@ -8,6 +8,7 @@ import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -19,9 +20,9 @@ public class NettyInitializer extends ChannelInitializer { ...@@ -19,9 +20,9 @@ public class NettyInitializer extends ChannelInitializer {
@Override @Override
protected void initChannel(Channel channel) throws Exception { protected void initChannel(Channel channel) throws Exception {
//创建一个通道初始化对象(匿名对象) //创建一个通道初始化对象(匿名对象)
//给pipeline 设置处理器 //给pipeline设置处理器
//可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue //可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue
//或者 scheduleTaskQueue //或者ScheduleTaskQueue
log.info("客户SocketChannel hashcode=" + channel.hashCode()); log.info("客户SocketChannel hashcode=" + channel.hashCode());
//websocket协议本身是基于http协议的,所以这边也要使用http解编码器 //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
...@@ -29,9 +30,13 @@ public class NettyInitializer extends ChannelInitializer { ...@@ -29,9 +30,13 @@ public class NettyInitializer extends ChannelInitializer {
//以块的方式来写的处理器 //以块的方式来写的处理器
channel.pipeline().addLast(new ChunkedWriteHandler()); channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024)); channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
channel.pipeline().addLast(new IdleStateHandler(10, 0, 0));
//WebSocket 数据压缩 ,压缩来自 client //WebSocket 数据压缩 ,压缩来自 client
channel.pipeline().addLast(new WebSocketServerCompressionHandler()); channel.pipeline().addLast(new WebSocketServerCompressionHandler());
channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10)); channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
channel.pipeline().addLast(new NettyServerHandler());//自定义消息处理类
//自定义消息处理类
channel.pipeline().addLast(new NettyTokenHandler());
channel.pipeline().addLast(new NettyServerHandler());
} }
} }
...@@ -10,11 +10,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannel; ...@@ -10,11 +10,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class CoordinationNettyServer { public class NettyServer {
private final int port; private final int port;
public CoordinationNettyServer(int port) { public NettyServer(int port) {
this.port = port; this.port = port;
} }
......
package cn.com.glsx.notify.netty; package cn.com.glsx.notify.netty;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.util.JwtUtils;
import io.netty.channel.*; import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
...@@ -23,6 +34,9 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter { ...@@ -23,6 +34,9 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static Lock lock_4 = new ReentrantLock(); private static Lock lock_4 = new ReentrantLock();
@Autowired
private JwtUtils jwtUtils;
/** /**
* 管理一个全局map,保存连接进服务端的通道数量 * 管理一个全局map,保存连接进服务端的通道数量
*/ */
...@@ -109,10 +123,32 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter { ...@@ -109,10 +123,32 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
lock_4.lock(); lock_4.lock();
try { try {
String socketString = ctx.channel().remoteAddress().toString(); String socketString = ctx.channel().remoteAddress().toString();
//
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
//协议握手成功完成
log.info("NettyWebSocketHandler.userEventTriggered --> : 协议握手成功完成");
//检查用户token
AttributeKey<String> attributeKey = AttributeKey.valueOf(HttpHeaders.AUTHORIZATION);
//从通道中获取用户token
String token = ctx.channel().attr(attributeKey).get();
if (StringUtils.isNotEmpty(token)) {
boolean flag = jwtUtils.verifyToken(token);
//校验token逻辑
if (flag) {
//如果token校验不通过,发送连接关闭的消息给客户端,设置自定义code和msg用来区分下服务器是因为token不对才导致关闭
ctx.writeAndFlush(new CloseWebSocketFrame(SystemMessage.NOT_LOGIN.getCode(), JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg())))).addListener(ChannelFutureListener.CLOSE);
}
}
}
//通过判断IdleStateEvent的状态来实现自己的读空闲,写空闲,读写空闲处理逻辑
if (evt instanceof IdleStateEvent) { if (evt instanceof IdleStateEvent) {
//读空闲,关闭通道
log.info("NettyWebSocketHandler.userEventTriggered --> : 读空闲,关闭通道");
IdleStateEvent event = (IdleStateEvent) evt; IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) { if (event.state() == IdleState.READER_IDLE) {
log.info("Client: " + socketString + " READER_IDLE 读超时"); log.info("Client: " + socketString + " READER_IDLE 读超时");
ctx.writeAndFlush(new TextWebSocketFrame("读超时")).addListener(ChannelFutureListener.CLOSE);
ctx.disconnect(); ctx.disconnect();
} else if (event.state() == IdleState.WRITER_IDLE) { } else if (event.state() == IdleState.WRITER_IDLE) {
log.info("Client: " + socketString + " WRITER_IDLE 写超时"); log.info("Client: " + socketString + " WRITER_IDLE 写超时");
...@@ -121,6 +157,7 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter { ...@@ -121,6 +157,7 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
log.info("Client: " + socketString + " ALL_IDLE 总超时"); log.info("Client: " + socketString + " ALL_IDLE 总超时");
ctx.disconnect(); ctx.disconnect();
} }
//ctx.close();
} }
} finally { } finally {
lock_4.unlock(); lock_4.unlock();
......
package cn.com.glsx.notify.netty;
import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import java.util.Map;
@Slf4j
public class NettyTokenHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
Map<CharSequence, CharSequence> queryMap = UrlBuilder.ofHttp(msg.uri()).getQuery().getQueryMap();
CharSequence token = queryMap.get(HttpHeaders.AUTHORIZATION);
if (token == null) {
token = msg.headers().get(HttpHeaders.AUTHORIZATION);
}
//提前结束传递,关闭连接
//if (token == null || !token.equals("1")) {
// ctx.writeAndFlush("token错误").addListener(ChannelFutureListener.CLOSE);
// return;
//}
ctx.channel().attr(AttributeKey.valueOf(HttpHeaders.AUTHORIZATION)).setIfAbsent(token.toString());
ctx.fireChannelRead(msg.retain());
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!