package org.wdzl.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;
import org.wdzl.SpringUtil;
import org.wdzl.enums.MsgActionEnum;
import org.wdzl.pojo.User;
import org.wdzl.services.UserServices;
import org.wdzl.utils.JsonUtils;
import java.util.ArrayList;
import java.util.List;
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
String content = msg.text();
DataContent dataContent = JsonUtils.jsonToPojo(content, DataContent.class);
Integer action = dataContent.getAction();
Channel channel = ctx.channel();
if(action == MsgActionEnum.CONNECT.type){
String senderId = dataContent.getChatMsg().getSenderId();
UserChanelRel.put(senderId,channel);
for (Channel c: users) {
System.out.println(c.id().asLongText());
}
UserChanelRel.output();
} else if(action == MsgActionEnum.CHAT.type){
ChatMsg chatMsg = dataContent.getChatMsg();
String msgContent = chatMsg.getMsg();
String senderId = chatMsg.getSenderId();
String receiverId = chatMsg.getReceiverId();
UserServices userServices = (UserServices) SpringUtil.getBean("userServicesImpl");
String msgId = userServices.saveMsg(chatMsg);
chatMsg.setMsgId(msgId);
DataContent dataContentMsg = new DataContent();
dataContentMsg.setChatMsg(chatMsg);
Channel receiverChannel = UserChanelRel.get(receiverId);
if(receiverChannel ==null){
}else{
Channel findChanel = users.find(receiverChannel.id());
if(findChanel!=null){
receiverChannel.writeAndFlush(
new TextWebSocketFrame(
JsonUtils.objectToJson(dataContentMsg)
)
);
}else{
}
}
} else if(action == MsgActionEnum.SIGNED.type){
UserServices userServices = (UserServices) SpringUtil.getBean("userServicesImpl");
String msgIdsStr = dataContent.getExtand();
String[] msgsId = msgIdsStr.split(",");
List<String> msgIdList = new ArrayList<>();
for (String mid: msgsId) {
if(StringUtils.isNotBlank(mid)){
msgIdList.add(mid);
}
}
System.out.println(msgIdList.toString());
if(msgIdList!=null && !msgIdList.isEmpty() && msgIdList.size()>0){
userServices.updateMsgSigned(msgIdList);
}
} else if(action == MsgActionEnum.KEEPALIVE.type){
System.out.println("收到来自channel 为【"+channel+"】的心跳包");
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
users.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
String chanelId = ctx.channel().id().asShortText();
System.out.println("客户端被移除:channel id 为:"+chanelId);
users.remove(ctx.channel());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.channel().close();
users.remove(ctx.channel());
}
}
package org.wdzl.netty;
import java.io.Serializable;
public class ChatMsg implements Serializable {
private String senderId;
private String receiverId;
private String msg;
private String msgId;
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
}
package org.wdzl.netty;
import java.io.Serializable;
public class DataContent implements Serializable {
private Integer action;
private ChatMsg chatMsg;
private String extand;
public Integer getAction() {
return action;
}
public void setAction(Integer action) {
this.action = action;
}
public ChatMsg getChatMsg() {
return chatMsg;
}
public void setChatMsg(ChatMsg chatMsg) {
this.chatMsg = chatMsg;
}
public String getExtand() {
return extand;
}
public void setExtand(String extand) {
this.extand = extand;
}
}
package org.wdzl.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;
import org.wdzl.SpringUtil;
import org.wdzl.enums.MsgActionEnum;
import org.wdzl.services.UserServices;
import org.wdzl.utils.JsonUtils;
import java.util.ArrayList;
import java.util.List;
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
IdleStateEvent event = (IdleStateEvent)evt;
if(event.state()== IdleState.READER_IDLE){
System.out.println("进入读空闲......");
}else if(event.state() == IdleState.WRITER_IDLE) {
System.out.println("进入写空闲......");
}else if(event.state()== IdleState.ALL_IDLE){
System.out.println("channel 关闭之前:users 的数量为:"+ChatHandler.users.size());
Channel channel = ctx.channel();
channel.close();
System.out.println("channel 关闭之后:users 的数量为:"+ChatHandler.users.size());
}
}
}
}
package org.wdzl.netty;
import io.netty.channel.Channel;
import java.util.HashMap;
import java.util.Map;
public class UserChanelRel {
private static HashMap<String, Channel> manage = new HashMap<>();
public static void put(String senderId,Channel channel){
manage.put(senderId,channel);
}
public static Channel get(String senderId){
return manage.get(senderId);
}
public static void output(){
for (Map.Entry<String,Channel> entry :manage.entrySet()) {
System.out.println("UserId:"+entry.getKey()
+",ChannelId:"+entry.getValue().id().asLongText()
);
}
}
}
package org.wdzl.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;
@Component
public class WebSocketServer {
private static class SingletionWSServer {
static final WebSocketServer instance = new WebSocketServer();
}
public static WebSocketServer getInstance() {
return SingletionWSServer.instance;
}
private EventLoopGroup mainGroup;
private EventLoopGroup subGroup;
private ServerBootstrap server;
private ChannelFuture future;
public WebSocketServer() {
mainGroup = new NioEventLoopGroup();
subGroup = new NioEventLoopGroup();
server = new ServerBootstrap();
server.group(mainGroup, subGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WSServerInitialzer());
}
public void start() {
this.future = server.bind("172.17.9.194",8888);
if (future.isSuccess()) {
System.out.println("启动 Netty 成功");
}
}
}
package org.wdzl.netty;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(1024*64));
pipeline.addLast(new IdleStateHandler(8,10,12));
pipeline.addLast(new HeartBeatHandler());
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new ChatHandler());
}
}