Commit 45f8f015 by levphon

集成netty,支持websocket

1 parent 178e8fbe
Showing 20 changed files with 470 additions and 177 deletions
......@@ -41,6 +41,10 @@
<groupId>com.glsx</groupId>
<artifactId>rest-admin-im</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger2</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
......
package cn.com.glsx;
import cn.com.glsx.notify.netty.CoordinationNettyServer;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
......@@ -7,7 +8,9 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
......@@ -18,6 +21,8 @@ import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableAsync
@EnableWebSocket
@EnableRestAdmin
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
......@@ -30,8 +35,7 @@ public class Application {
SpringApplication.run(Application.class, args);
//启动NettyServer服务端
// NettyServer nettyServer = new NettyServer();
// nettyServer.run();
new CoordinationNettyServer(9779).start();
}
@PostConstruct
......
package cn.com.glsx.notify.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author payu
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
\ No newline at end of file
package cn.com.glsx.notify.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
//package cn.com.glsx.notify.config;
//
//import cn.com.glsx.notify.modules.websocket.handler.MessageHandler;
//import cn.com.glsx.notify.modules.websocket.handler.PersistenceToDatabaseWebSocketHandlerDecorator;
//import cn.com.glsx.notify.modules.websocket.handler.PersistenceToElasticsearchWebSocketHandlerDecorator;
//import cn.com.glsx.notify.modules.websocket.handler.TextHandler;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.socket.WebSocketHandler;
//import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
//import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
//
//@Configuration
public class WebSocketConfig {
//public class WebSocketConfig implements WebSocketConfigurer {
//
// @Override
// public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// registry.addHandler(buildMessageHandler(), "/ws/asset")
// //复制HttpSession中的属性到WebSocketSession中
//// .addInterceptors(new RbacHandshakeInterceptor())
// .addInterceptors(new HttpSessionHandshakeInterceptor())
// .setAllowedOrigins("*");
// }
//
// @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
\ No newline at end of file
// public WebSocketHandler buildTextHandler() {
// return new TextHandler();
// }
//
// @Bean
// public WebSocketHandler buildMessageHandler() {
// return new PersistenceToElasticsearchWebSocketHandlerDecorator(new PersistenceToDatabaseWebSocketHandlerDecorator(new MessageHandler()));
// }
//
//}
\ No newline at end of file
/*
package cn.com.glsx.notify.modules.controller;
import lombok.EqualsAndHashCode;
......@@ -15,12 +14,12 @@ import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Component
@EqualsAndHashCode
@ServerEndpoint(value = "/ws/asset")
@ServerEndpoint(value = "/ws")
public class WebSocketServer {
@PostConstruct
public void init() {
log.info("websocket 加载");
log.info("WebSocket 加载");
}
private Session session;
......@@ -31,11 +30,9 @@ public class WebSocketServer {
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
*/
/**
/**
* 连接建立成功调用的方法
*//*
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
......@@ -50,11 +47,9 @@ public class WebSocketServer {
SendMessage(session, "连接成功");
}
*/
/**
/**
* 连接关闭调用的方法
*//*
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
......@@ -64,41 +59,35 @@ public class WebSocketServer {
log.info("有连接关闭,当前连接数为:{}", cnt);
}
*/
/**
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*//*
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:{}", message);
SendMessage(session, "收到消息,消息内容:" + message);
}
*/
/**
/**
* 出现错误
*
* @param session
* @param error
*//*
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
}
*/
/**
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
* @param session
* @param message
*//*
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
......@@ -108,14 +97,12 @@ public class WebSocketServer {
}
}
*/
/**
/**
* 群发消息
*
* @param message
* @throws IOException
*//*
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if (session.isOpen()) {
......@@ -124,15 +111,13 @@ public class WebSocketServer {
}
}
*/
/**
/**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*//*
*/
public static void SendMessage(String message, String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
......@@ -152,4 +137,3 @@ public class WebSocketServer {
this.session.getBasicRemote().sendText(message);
}
}
*/
/*
package cn.com.glsx.notify.modules.kafka;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
......@@ -12,17 +11,15 @@ import java.util.Optional;
import static cn.com.glsx.notify.modules.controller.WebSocketServer.SocketSet;
*/
/**
* @author payu
*//*
*/
@Slf4j
@Component
public class MessageConsumer {
@KafkaListener(id = "messageConsumer",
topics = "#{'${topic.message.application}'.split(',')}",
@KafkaListener(id = "messageConsumer", topics = "#{'${topic.message.application}'.split(',')}",
errorHandler = "consumerAwareErrorHandler")
public void listener(ConsumerRecord<?, ?> record) {
//errorHandler异常处理器注解里面使用的也是bean的名称
......@@ -45,4 +42,3 @@ public class MessageConsumer {
}
}
*/
/*
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.dto.PCTemplateMessageDTO;
import cn.com.glsx.notify.modules.model.PCTemplateMessageDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
......@@ -12,11 +12,10 @@ import org.springframework.util.concurrent.ListenableFutureCallback;
import javax.annotation.Resource;
*/
/**
* @author payu
*//*
*/
@Slf4j
@Service
public class PCService {
......@@ -45,4 +44,4 @@ public class PCService {
}
}
*/
package cn.com.glsx.notify.modules.websocket.handler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@Slf4j
public class MessageHandler extends AbstractWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
SessionManager.put(session.getId(), session);
log.info("session[{}] afterConnectionEstablished", session.getId());
log.info("get WebSocketSession attributes={}",session.getAttributes());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.info("session[{}] afterConnectionClosed", session.getId());
SessionManager.remove(session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
log.info("session[{}] receive text message={}", session.getId(), message);
//for test error
if(message.getPayload().equals("error")){
throw new RuntimeException(this.getClass().getSimpleName()+".handleTextMessage error");
}
}
@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
log.info("session[{}] receive binary message={} length={}", session.getId(), message, message.getPayloadLength());
}
@Override
protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
log.info("session[{}] receive pong message={}", session.getId(), message);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
}
package cn.com.glsx.notify.modules.websocket.handler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
@Slf4j
public class PersistenceToDatabaseWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
public PersistenceToDatabaseWebSocketHandlerDecorator(WebSocketHandler delegate) {
super(delegate);
}
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
try {
this.getDelegate().handleMessage(session, message);
} catch (Exception e) {
e.printStackTrace();
}
if (message instanceof TextMessage) {
log.debug("save text message[{}] to database", message.getPayload());
//todo 这里可以基于任意的jdbc框架来写库
} else if (message instanceof BinaryMessage) {
log.debug("save binary message to database");
}
}
}
package cn.com.glsx.notify.modules.websocket.handler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
@Slf4j
public class PersistenceToElasticsearchWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
public PersistenceToElasticsearchWebSocketHandlerDecorator(WebSocketHandler delegate) {
super(delegate);
}
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
try {
this.getDelegate().handleMessage(session, message);
} catch (Exception e) {
e.printStackTrace();
}
if (message instanceof TextMessage) {
log.debug("save text message[{}] to elasticsearch", message.getPayload());
//todo 这里可以基于任意的elasticsearch框架来写入搜索引擎
} else if (message instanceof BinaryMessage) {
log.debug("save binary message to elasticsearch");
}
}
}
package cn.com.glsx.notify.modules.websocket.handler;
import org.springframework.web.socket.WebSocketSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class SessionManager {
private static final Map<String, WebSocketSession> sessions = new HashMap<>();
private SessionManager() {
}
public static WebSocketSession put(String key,WebSocketSession webSocketSession) {
return sessions.put(key,webSocketSession);
}
public static Set<String> sessions() {
return sessions.keySet();
}
public static WebSocketSession get(String key) {
return sessions.get(key);
}
public static WebSocketSession remove(String key) {
return sessions.remove(key);
}
}
package cn.com.glsx.notify.modules.websocket.handler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Slf4j
public class TextHandler extends TextWebSocketHandler {
private static final String HEARTBEAT_PING = "PING";
private static final String HEARTBEAT_PONG = "PONG";
private static final TextMessage HEARTBEAT_PONG_MESSAGE = new TextMessage(HEARTBEAT_PONG);
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
if (session.isOpen()) {
log.info("receive websocket message:{} session:{}", message, session.getId());
if (message.getPayload().equals(HEARTBEAT_PING)) {
session.sendMessage(HEARTBEAT_PONG_MESSAGE);
} else {
TextMessage returnMessage = new TextMessage(message.getPayload() + " received at server");
session.sendMessage(returnMessage);
}
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
SessionManager.put(session.getId(), session);
log.info("session[{}] afterConnectionEstablished", session.getId());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.info("session[{}] afterConnectionClosed", session.getId());
SessionManager.remove(session.getId());
}
}
package cn.com.glsx.notify.modules.websocket.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
@Slf4j
public class RbacHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
log.debug("beforeHandshake {} to {} websocket request", serverHttpRequest.getMethodValue(), serverHttpRequest.getURI());
log.debug("serverHttpRequest.getHeaders()={}", serverHttpRequest.getHeaders());
// boolean result = handleByCookie(serverHttpRequest);
boolean result = handleByQueryString(serverHttpRequest);
// boolean result = handleByHttpSession(serverHttpRequest);
if (!result) {
serverHttpResponse.setStatusCode(HttpStatus.FORBIDDEN);
}
return result;
}
private boolean handleByCookie(ServerHttpRequest serverHttpRequest) {
if (serverHttpRequest instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) serverHttpRequest;
Cookie[] cookies = servletServerHttpRequest.getServletRequest().getCookies();
Optional<Cookie> cookie = Arrays.stream(cookies).filter(c -> c.getName().equals("token")).findFirst();
if (cookie.isPresent()) {
String token = cookie.get().getValue();
log.debug("find token from cookie={}", token);
//todo parse value
return true;
} else {
log.warn("not found token from cookie");
return false;
}
}
return false;
}
private boolean handleByQueryString(ServerHttpRequest serverHttpRequest) {
if (serverHttpRequest instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) serverHttpRequest;
String token = servletServerHttpRequest.getServletRequest().getParameter("token");
if (StringUtils.hasLength(token)) {
log.debug("find token from querystring={}", token);
//todo parse value
return true;
} else {
log.warn("not found token from querystring");
return false;
}
}
return false;
}
private boolean handleByHttpSession(ServerHttpRequest serverHttpRequest) {
if (serverHttpRequest instanceof ServletServerHttpRequest) {
HttpSession httpSession = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getSession();
if (httpSession.getAttribute("isLogin") != null && (Boolean) (httpSession.getAttribute("isLogin"))) {
log.debug("check session login success");
return true;
} else {
log.debug("check session login fail");
return false;
}
}
return false;
}
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
log.debug("afterHandshake {}", serverHttpRequest.getURI());
}
}
\ No newline at end of file
/*
package cn.com.glsx.notify.netty;
import io.netty.bootstrap.ServerBootstrap;
......@@ -9,22 +8,20 @@ import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@Configuration
public class NettyServer {
public class CoordinationNettyServer {
@Value("${netty.server.port}")
private Integer port;
private final int port;
final EventLoopGroup bossGroup = new NioEventLoopGroup();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
public CoordinationNettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
final EventLoopGroup bossGroup = new NioEventLoopGroup();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
public void run() throws Exception {
//创建BossGroup 和 WorkerGroup
//说明
//1. 创建两个线程组 bossGroup 和 workerGroup
......@@ -40,36 +37,36 @@ public class NettyServer {
bootstrap.group(bossGroup, workerGroup)
//使用NioSocketChannel 作为服务器的通道实现
.channel(NioServerSocketChannel.class)
// 设置线程队列得到连接个数(也可以说是并发数)
//设置线程队列得到连接个数(也可以说是并发数)
.option(ChannelOption.SO_BACKLOG, 2048)
//设置保持活动连接状态
.childOption(ChannelOption.SO_KEEPALIVE, true)
//.handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
//.childOption(ChannelOption.TCP_NODELAY,true)//socketchannel的设置,关闭延迟发送
//绑定监听端口
.localAddress(this.port)
//该handler对应bossGroup,childHandler对应workerGroup
//.handler(null)
//socketchannel的设置,关闭延迟发送
//.childOption(ChannelOption.TCP_NODELAY,true)
.childHandler(new NettyInitializer());
log.info(".....NettyServer is ready.....");
log.info(".....服务器 is ready.....");
//绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
//启动服务器(并绑定端口)
ChannelFuture cf = bootstrap.bind(port).sync();
//启动服务器(并绑定端口), 生成 ChannelFuture 对象
ChannelFuture cf = bootstrap.bind().sync();
//给cf 注册监听器,监控我们关心的事件
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (cf.isSuccess()) {
log.info("监听端口[{}]成功!", port);
} else {
log.error("监听端口[{}]失败!", port);
}
cf.addListener((ChannelFutureListener) future -> {
if (cf.isSuccess()) {
log.info("监听端口[{}]成功!", port);
} else {
log.error("监听端口[{}]失败!", port);
}
});
//对关闭通道进行监听
cf.channel().closeFuture().sync();
} catch (Exception e) {
log.error(" netty服务启动异常 " + e.getMessage());
log.error(" NettyServer启动异常 " + e.getMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}*/
}
/*
package cn.com.glsx.notify.netty;
import io.netty.buffer.ByteBuf;
......@@ -18,4 +17,4 @@ public class MyByteEncoder extends MessageToByteEncoder<byte[]> {
//字节数组
out.writeBytes(bytes);
}
}*/
}
/*
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
......@@ -8,28 +7,26 @@ import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class NettyDataSvervice {
public class NettyDataService {
private static final ReentrantLock Lock = new ReentrantLock();
*/
/**
/**
* 将传送过来的数据进行解析,包括异或运算 (第一次服务器端给客户端发)
*
* @param receiveData
* @return
*//*
*/
public static String sendData(String receiveData) {
final ReentrantLock putLock = Lock;
log.info("接收数据" + receiveData);
putLock.lock();
try {
//此处需要读数据进行校验以及分包黏包处理,本文主要提供思路所以省略
*/
/*
* 处理分包黏包、拆分、解析等
*//*
/*
*处理分包黏包、拆分、解析等
*/
//数据解析
parseData(receiveData);
......@@ -45,13 +42,12 @@ public class NettyDataSvervice {
}
}
*/
/**
* 数据入库处理
*//*
/**
* 数据入库处理
*/
public static void parseData(String receiveData) {
System.out.println("执行入库操作");
}
}
*/
/*
package cn.com.glsx.notify.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
......@@ -13,9 +16,6 @@ import org.springframework.stereotype.Component;
@ChannelHandler.Sharable
public class NettyInitializer extends ChannelInitializer {
@Autowired
public MyByteEncoder myByteEncoder;
@Override
protected void initChannel(Channel channel) throws Exception {
//创建一个通道初始化对象(匿名对象)
......@@ -27,6 +27,15 @@ public class NettyInitializer extends ChannelInitializer {
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//出站编码
channel.pipeline().addLast(new MyByteEncoder());
channel.pipeline().addLast(new NettyServerHandler());
//websocket协议本身是基于http协议的,所以这边也要使用http解编码器
channel.pipeline().addLast(new HttpServerCodec());
//以块的方式来写的处理器
channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
//WebSocket 数据压缩 ,压缩来自 client
channel.pipeline().addLast(new WebSocketServerCompressionHandler());
channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
channel.pipeline().addLast(new NettyServerHandler());//自定义消息处理类
}
}*/
}
/*
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import com.glsx.plat.common.utils.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalTime;
import java.util.Objects;
@Slf4j
public class NettySendThread implements Runnable {
private ChannelHandlerContext ctx;
private String data;
private Object data;
public NettySendThread(ChannelHandlerContext ctx, String data) {
public NettySendThread(ChannelHandlerContext ctx, Object data) {
this.ctx = ctx;
this.data = data;
}
@Override
public void run() {
String bcc = NettyDataSvervice.sendData(data);
log.info("接收需要返回的消息:" + bcc);
if (Objects.isNull(bcc)) {
if (data instanceof ByteBuf) {
//将 msg 转成一个 ByteBuf
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ByteBuf buf = (ByteBuf) data;
//得到此时客户端的数据长度
int bytes_length = buf.readableBytes();
//组件新的字节数组
byte[] buffer = new byte[bytes_length];
buf.readBytes(buffer);
String allData = NettyByteAndStringUtils.byteToHex(buffer);
log.info("进入服务端数据:" + allData);
String reply = NettyDataService.sendData(allData);
log.info("接收需要返回的消息:" + reply);
if (StringUtils.isNullOrEmpty(reply)) {
return;
}
//数据的发送与接收都是16进制
byte[] sendData = NettyByteAndStringUtils.hexToByte(reply);
log.info("发送数据时间: " + LocalTime.now());
ctx.writeAndFlush(sendData);
} else if (data instanceof TextWebSocketFrame) {
TextWebSocketFrame frame = (TextWebSocketFrame) data;
String allData = frame.text();
log.info("进入服务端数据:" + allData);
String reply = null;
if ("你好".equals(allData)) {
reply = "你好";
}
if ("在干吗".equals(allData)) {
reply = "学习";
}
if (StringUtils.isNullOrEmpty(reply)) {
return;
}
TextWebSocketFrame webSocketFrame = new TextWebSocketFrame(reply);
//写回数据也是按照协议格式写TextWebSocketFrame
ctx.writeAndFlush(webSocketFrame);
} else {
return;
}
//数据的发送与接收都是16进制
byte[] sendData = NettyByteAndStringUtils.hexToByte(bcc);
log.info("发送数据时间: " + LocalTime.now());
ctx.writeAndFlush(sendData);
}
}
*/
/*
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
......@@ -26,11 +23,9 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static Lock lock_4 = new ReentrantLock();
*/
/**
/**
* 管理一个全局map,保存连接进服务端的通道数量
*//*
*/
private static final ConcurrentHashMap<ChannelId, ChannelHandlerContext> CHANNEL_MAP = new ConcurrentHashMap<>();
@Override //数据读取完毕
......@@ -41,29 +36,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
}
*/
/**
/**
* 处理异常, 一般是需要关闭通道
*
* @param ctx
* @param cause
* @throws Exception
*//*
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
log.info("服务端异常关闭" + ctx.channel());
log.info("服务端{}异常关闭,异常信息:{}", ctx.channel(), cause.getMessage());
}
*/
/**
/**
* @param ctx
* @DESCRIPTION: 有客户端连接服务器会触发此函数
* @return: void
*//*
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
lock_1.lock();
......@@ -85,13 +76,11 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
}
}
*/
/**
/**
* @param ctx
* @DESCRIPTION: 有客户端终止连接服务器会触发此函数
* @return: void
*//*
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
lock_2.lock();
......@@ -110,40 +99,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
}
}
*/
/**
/**
* 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
* 2. Object msg: 就是客户端发送的数据 默认Object
* <p>
* 读取数据实际(这里我们可以读取客户端发送的消息)
*//*
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
lock_3.lock();
try {
log.info("服务器读取线程 " + Thread.currentThread().getName() + " channle = " + ctx.channel());
Channel channel = ctx.channel();
//将 msg 转成一个 ByteBuf
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ByteBuf buf = (ByteBuf) msg;
//得到此时客户端的数据长度
int bytes_length = buf.readableBytes();
//组件新的字节数组
byte[] buffer = new byte[bytes_length];
buf.readBytes(buffer);
final String allData = NettyByteAndStringUtils.byteToHex(buffer);
log.info("进入服务端数据:" + allData);
ctx.executor().execute(new NettySendThread(ctx, allData));
log.info("服务器读取线程 " + Thread.currentThread().getName() + " channel = " + channel.toString());
ctx.executor().execute(new NettySendThread(ctx, msg));
} finally {
lock_3.unlock();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
lock_4.lock();
......@@ -166,4 +140,4 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
lock_4.unlock();
}
}
}*/
}
/*
package cn.com.glsx.notify.netty.utils;
import java.util.concurrent.locks.ReentrantLock;
......@@ -8,11 +7,9 @@ public class NettyByteAndStringUtils {
private final static ReentrantLock Lock = new ReentrantLock();
*/
/**
/**
* byte数组转hex
*//*
*/
public static String byteToHex(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
......@@ -30,11 +27,10 @@ public class NettyByteAndStringUtils {
}
}
*/
/**
* hex转byte数组
*//*
/**
* hex转byte数组
*/
public static byte[] hexToByte(String hex) {
final ReentrantLock putLock = Lock;
putLock.lock();
......@@ -55,11 +51,10 @@ public class NettyByteAndStringUtils {
}
}
*/
/**
* 字节数组的大小
*//*
/**
* 字节数组的大小
*/
public static int getByteSize(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
......@@ -80,4 +75,3 @@ public class NettyByteAndStringUtils {
}
}
}
*/
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!