package org.springblade.modules.nettyServer; import com.alibaba.fastjson.JSONObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import org.springblade.modules.webscoket.service.IPushMsgService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @Component public class ServerHandler extends ChannelInboundHandlerAdapter { private String reg_LA = "LA[d]{8}[d|A-F]{12}[d|A-F]{8}[d|A-Z]{2}[d|A-F]{4}[x2A][d|A-F]{6}[#@]"; private String reg_LB = "LB[\\d|A-F]{12}[\\x2A].*[#@]"; private String reg_LB2 = "LB[\\d|A-F]{6}[\\x2A].*[#@]"; private String reg_LD = "LD[d]{8}[d|A-F]{12}:[A-Z]{4}[\\x2A].*[#@]"; private ConcurrentHashMap sessionChannelMap = new ConcurrentHashMap(); private static ServerHandler serverHandler; @PostConstruct public void init() { serverHandler = this; } /** * 客户端与服务端创建连接的时候调用 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("CTX:" + ctx.channel()); System.out.println("客户端与服务端连接开始..."); } /** * 客户端与服务端断开连接时调用 */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("客户端与服务端连接关闭..."); NettyConfig.group.remove(ctx.channel()); } /** * 服务端接收客户端发送过来的数据结束之后调用 */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); System.out.println("信息接收完毕..."); } /** * 工程出现异常的时候调用 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } /** * 服务端处理客户端websocket请求的核心方法,这里接收了客户端发来的信息 */ @Override public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception { System.out.println("接收到了:" + info); ByteBuf buf = (ByteBuf) info; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); String content = body; System.out.println("接收客户端数据:" + body); } }