网络模块优化

back_recharge
zhangshanxue 2019-11-26 11:17:06 +08:00
parent 85eae5a303
commit ff37fa5d2c
15 changed files with 73 additions and 86 deletions

View File

@ -10,7 +10,7 @@ import java.util.Map;
*/
public class EndPortCfg {
private String host;
private String host="0.0.0.0";
private int port;
private Map<String, String> parameters = new HashMap<>();

View File

@ -59,7 +59,7 @@ public class ServerResponseMessageHandler extends SimpleChannelInboundHandler<Me
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
LOGGER.info("channelInactive->run");
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), this.handler);
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
try {
nettyChannel = channel;
this.handler.connected(channel);

View File

@ -19,10 +19,10 @@ import java.util.concurrent.ConcurrentHashMap;
* Author: zsx
* CreateDate: 2019/11/7 10:24
*/
public abstract class AbstractClient extends AbstractEndport {
public abstract class AbstractClient<T extends NettyGameSession> extends AbstractEndport {
protected Logger LOGGER = LoggerFactory.getLogger(AbstractClient.class);
//不对外暴露接口
private NettyGameSession gameSession;
private T gameSession;
private InetSocketAddress localAddress;
final int readTimeout;
final int writeTimeout;
@ -50,7 +50,7 @@ public abstract class AbstractClient extends AbstractEndport {
public void connected(IChannel channel) {
if (handler instanceof INetSession) {
NettyGameSession gameSession = ((INetSession) handler).createGameSession(channel, handler);
gameSession = ((INetSession<T>) handler).createGameSession(channel, handler);
if (null != gameSession) {
LOGGER.info("seission" + gameSession + "channelActive: " + gameSession.getChannel().getRemoteAddress() + " ,uid: " +
gameSession.getUid() + " ,areaId: " + gameSession.getAreaId());

View File

@ -70,13 +70,16 @@ public abstract class AbstractServer extends AbstractEndport {
public void disconnected(IChannel channel) {
String sessionId = channel.getBindSessionId();
if (handler instanceof INetConnet) {
NettyGameSession gameSession = this.currentSessions.remove(sessionId);
if (null != gameSession) {
LOGGER.info("channelInactive->uid={},seission={},remoteAddress={}",
gameSession.getUid(), gameSession, gameSession.getChannel().getRemoteAddress());
((INetConnet) handler).offLine(gameSession);
gameSession.close();
if(this.currentSessions.containsKey(sessionId)){
NettyGameSession gameSession = this.currentSessions.remove(sessionId);
if (null != gameSession) {
LOGGER.info("channelInactive->uid={},seission={},remoteAddress={}",
gameSession.getUid(), gameSession, gameSession.getChannel().getRemoteAddress());
((INetConnet) handler).offLine(gameSession);
gameSession.close();
}
}
}
}

View File

@ -86,10 +86,10 @@ public class NettyGameServer extends AbstractServer {
});
serverBootstrap.bind(getLocalAddress().getPort()).sync().channel().closeFuture().sync();
ChannelFuture channelFuture = serverBootstrap.bind(getLocalAddress().getPort());
this.channel = channelFuture.channel();
channelFuture.sync();
channelFuture.channel().closeFuture().sync();
// ChannelFuture channelFuture = serverBootstrap.bind(getLocalAddress().getPort());
// this.channel = channelFuture.channel();
// channelFuture.sync();
// channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
throw new ConnectException("close exception", getLocalAddress(), null);
} finally {

View File

@ -1,5 +1,6 @@
package com.ljsd.jieling.protocol;
import com.ljsd.jieling.netty.NettyGameSession;
import com.ljsd.jieling.session.GameSession;
/**
@ -7,9 +8,9 @@ import com.ljsd.jieling.session.GameSession;
* Author: zsx
* CreateDate: 2019/11/21 10:42
*/
public interface INetConnet {
public interface INetConnet<T extends NettyGameSession> {
void offLine(GameSession gameSession);
void offLine(T gameSession);
void readIdel(GameSession gameSession);
void readIdel(T gameSession);
}

View File

@ -7,6 +7,6 @@ import com.ljsd.jieling.netty.NettyGameSession;
* Author: zsx
* CreateDate: 2019/11/21 10:41
*/
public interface INetReceived {
void onReceive(NettyGameSession gameSession, Object obj) ;
public interface INetReceived<T extends NettyGameSession> {
void onReceive(T gameSession, Object obj) ;
}

View File

@ -8,8 +8,8 @@ import com.ljsd.jieling.netty.server.IChannel;
* Author: zsx
* CreateDate: 2019/11/5 17:07
*/
public interface INetSession {
NettyGameSession createGameSession(IChannel channel, INetWorkHandler handler);
void OnsessionAdd(NettyGameSession gameSession);
public interface INetSession<T extends NettyGameSession> {
void OnsessionAdd(T gameSession);
T createGameSession(IChannel channel, INetWorkHandler handler);
void OnsessionRemove(String id);
}

View File

@ -47,7 +47,6 @@ public class GameLogicService implements IService {
public void init() throws Exception {
RedisUtil.getInstence().init();
MongoUtil.getInstence().init();
registerServerInfoToRedis();
}
@ -72,6 +71,7 @@ public class GameLogicService implements IService {
//TODO 注册消息 抽象
//注册消息处理方法
ProtocolsManager protocolsManager = ProtocolsManager.getInstance();
protocolsManager.initHandler("com.ljsd.jieling.handler");
protocolsManager.initCheck();
// 追加ProtocolsManager消息处理器 注解和非注解

View File

@ -2,10 +2,8 @@ package com.ljsd.jieling.logic;
import com.ljsd.jieling.network.session.ISession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class OnlineUserManager {
@ -15,15 +13,6 @@ public class OnlineUserManager {
sessionMap.put(uid, session);
}
public static Object[] getSessionList() {
List<Integer> onlineList = new CopyOnWriteArrayList<>();
for (Map.Entry<Integer, ISession> entry :sessionMap.entrySet()){
Integer uid = entry.getKey();
onlineList.add(uid);
}
Object[] objects = onlineList.toArray();
return objects;
}
public static void userOffline(int uid) {
sessionMap.remove(uid);
@ -31,26 +20,28 @@ public class OnlineUserManager {
/**
* uidSession
*
* @param uid
* @return
*/
public static ISession getSessionByUid(int uid) {
if(sessionMap == null){
if (sessionMap == null) {
return null;
}
return sessionMap.get(uid);
return sessionMap.get(uid);
}
/**
* 线
*
* @param uid
* @return
*/
public static boolean checkUidOnline(int uid) {
if(sessionMap == null){
if (sessionMap == null) {
return false;
}
return sessionMap.containsKey(uid);
return sessionMap.containsKey(uid);
}
}

View File

@ -137,7 +137,7 @@ public class ActivityLogic {
if(user1==null){
return;
}
ISession session = OnlineUserManager.sessionMap.get(user1.getId());
ISession session = OnlineUserManager.getSessionByUid(user1.getId());
if(null ==session){
return;
}
@ -174,7 +174,7 @@ public class ActivityLogic {
public void newPlayerOpenActivityMission(User user) throws Exception {
checkActivityOfUser(user, null);
ISession session = OnlineUserManager.sessionMap.get(user.getId());
ISession session = OnlineUserManager.getSessionByUid(user.getId());
if (null != session)
sendLuckWheelPool(user, session);
}

View File

@ -40,7 +40,7 @@ public class NetManager implements IManager {
// nettyServer = new NettyGameServer(properties.getTcpPort(), properties.getReadTimeout(),
// properties.getWriteTimeout(), properties.getAllTimeout(), ProtocolsManager.getInstance(),
// sessionFactory);
// nettyServer.start();
nettyServer.start();
} catch (Exception e) {
LOGGER.error("main->msg={}", e.getMessage(), e);

View File

@ -52,20 +52,16 @@ public class ProtocolsManager implements ProtocolsAbstract {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolsManager.class);
private static ProtocolsManager instance = new ProtocolsManager();
private static Map<Integer, BaseHandler> handlers = new HashMap<>();
private Map<Integer, BaseHandler> handlers = new HashMap<>();
private static ClassLoader classLoader = GameApplication.class.getClassLoader();
public final static int HANDLER_THREAD_NUM = 50;
public static HandlerLogicThread[] handlerThreads = new HandlerLogicThread[HANDLER_THREAD_NUM];
public HandlerLogicThread[] handlerThreads = new HandlerLogicThread[HANDLER_THREAD_NUM];
static {
initHandler("com.ljsd.jieling.handler");
private ProtocolsManager() {
initContext();
}
private ProtocolsManager() {
}
public static void initContext() {
public void initContext() {
for (int i = 0; i < HANDLER_THREAD_NUM; i++) {
handlerThreads[i] = new HandlerLogicThread();
handlerThreads[i].setPriority(9);//优先级最高
@ -83,13 +79,13 @@ public class ProtocolsManager implements ProtocolsAbstract {
}
public static void addHandler(BaseHandler handler) {
private void addHandler(BaseHandler handler) {
handlers.put(handler.getMessageCode().getNumber(), handler);
}
public static void processMessage(PacketNetData packetNetData) {
public void processMessage(PacketNetData packetNetData) {
//
//<<<<<<< HEAD
//=======
@ -191,7 +187,7 @@ public class ProtocolsManager implements ProtocolsAbstract {
public static boolean addEntry(PacketNetData packetNetData) {
public boolean addEntry(PacketNetData packetNetData) {
int userId = packetNetData.getUserId();
try {
@ -731,7 +727,7 @@ public class ProtocolsManager implements ProtocolsAbstract {
}
private static void initHandler(String pck){
public void initHandler(String pck){
List<Class<?>> handlers = new LinkedList<>();
try
{

View File

@ -16,18 +16,15 @@ import com.ljsd.jieling.logic.dao.PlayerManager;
import com.ljsd.jieling.logic.dao.UserManager;
import com.ljsd.jieling.logic.dao.root.User;
import com.ljsd.jieling.logic.family.GuildLogic;
import com.ljsd.jieling.netty.NettyGameSession;
import com.ljsd.jieling.netty.cocdex.PacketNetData;
import com.ljsd.jieling.netty.handler.GameMessageHandler;
import com.ljsd.jieling.netty.server.IChannel;
import com.ljsd.jieling.netty.server.NettyChannel;
import com.ljsd.jieling.network.session.ISession;
import com.ljsd.jieling.protocol.INetConnet;
import com.ljsd.jieling.protocol.INetReceived;
import com.ljsd.jieling.protocol.INetWorkHandler;
import com.ljsd.jieling.protocols.MessageTypeProto;
import com.ljsd.jieling.protocol.INetSession;
import com.ljsd.jieling.session.GameSession;
import com.ljsd.jieling.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -52,9 +49,9 @@ import java.util.concurrent.ConcurrentHashMap;
* Author: zsx
* CreateDate: 2019/11/5 17:05
*/
public class SessionManager implements INetSession, INetReceived, INetConnet, INetWorkHandler {
public class SessionManager implements INetSession<ISession>, INetReceived<ISession>, INetConnet<ISession>, INetWorkHandler {
private final Map<String, NettyGameSession> currentSessions = new ConcurrentHashMap<>();
private Map<String, ISession> currentSessions = new ConcurrentHashMap<>();
private static final Logger LOGGER = LoggerFactory.getLogger(SessionManager.class);
@ -64,8 +61,7 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
return instance;
}
@Override
public void OnsessionAdd(NettyGameSession gameSession) {
public void OnsessionAdd(ISession gameSession) {
currentSessions.put(gameSession.getId(),gameSession);
}
@ -74,13 +70,12 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
currentSessions.remove(id);
}
public void onReceive(NettyGameSession gameSession, Object obj) {
@Override
public void onReceive(ISession session, Object obj) {
if (!GameApplication.start) {
return;
}
final ISession session = (ISession) gameSession;
PacketNetData packetNetData = new PacketNetData((byte[]) obj);
if (packetNetData.getMsgId() == 1000) {
session.setHeartBreatNums(3);
@ -97,9 +92,10 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
LOGGER.info("request={} commond ={}: ", packetNetData.getUserId(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()));
if (packetNetData.getMsgId() == MessageTypeProto.MessageType.LOGIN_REQUEST_VALUE ||
packetNetData.getMsgId() == MessageTypeProto.MessageType.RECONNECT_REQUEST_VALUE) {
if (onLoginORReLoginRequest(session, packetNetData)) {
if (!onLoginORReLoginRequest(session, packetNetData)) {
return;
}
//在线列表加入session
OnlineUserManager.userOnline(session.getUid(), session);
}
@ -122,7 +118,7 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
return;
}
ProtocolsManager.processMessage(packetNetData);
ProtocolsManager.getInstance().processMessage(packetNetData);
}
@ -149,7 +145,7 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
return false;
}
//处理多设备重登
if (onRepeatLogin(session) == 1 && packetNetData.getMsgId() != MessageTypeProto.MessageType.RECONNECT_REQUEST_VALUE) {
if (onRepeatLogin(session) == 1) {
return false;
}
return true;
@ -248,15 +244,15 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
int index = packetNetData.getIndex();
if (iSession.getIndex() >= index) {
byte[] message = iSession.getCacheMessage(index);
if (message == null) {
//TODO error
LOGGER.info("the uid={},the msg={} is processing,the index={},the sessionIndex={}", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()), index, iSession.getIndex());
return 1;
} else {
LOGGER.info("the uid={},the msg={} reback", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()));
iSession.writeAndFlush(message);
return 1;
}
// if (message == null) {
// //TODO error
// LOGGER.info("the uid={},the msg={} is processing,the index={},the sessionIndex={}", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()), index, iSession.getIndex());
// return 1;
// } else {
// LOGGER.info("the uid={},the msg={} reback", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()));
// iSession.writeAndFlush(message);
// return 1;
// }
} else {
iSession.setIndex(index);
iSession.setLoginTime(System.currentTimeMillis());
@ -275,11 +271,10 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
OnlineUserManager.userOffline(session.getUid());
}
@Override
public void offLine(GameSession gameSession) {
public void offLine(ISession session) {
ISession session = (ISession) gameSession;
LOGGER.info("player offLine ..{}",session.getUid());
synchronized (gameSession) {
synchronized (session) {
if (session.getUid() == 0) {
LOGGER.error("offLine->uid={}", session.getUid());
return;
@ -307,8 +302,7 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
}
@Override
public void readIdel(GameSession gameSession) {
final ISession iSession = (ISession) gameSession;
public void readIdel(ISession iSession) {
//对端口扫描直接关闭
if (iSession.getUid() == 0) {
iSession.close();
@ -364,7 +358,7 @@ public class SessionManager implements INetSession, INetReceived, INetConnet, IN
}
@Override
public NettyGameSession createGameSession(IChannel channel, INetWorkHandler handler) {
public ISession createGameSession(IChannel channel, INetWorkHandler handler) {
return new ISession(channel, handler);
}

View File

@ -4,7 +4,6 @@ import com.ljsd.jieling.logic.OnlineUserManager;
import com.ljsd.jieling.network.session.ISession;
import com.ljsd.jieling.protocols.MessageTypeProto;
import com.ljsd.jieling.util.MessageUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import util.TimeUtils;
import org.slf4j.Logger;
@ -42,9 +41,12 @@ public class RetrySendIndicationThread extends Thread{
long now = TimeUtils.now();
Set<Integer> removeIds = new HashSet<>();
for(ISession session : sessionMap.values()){
ChannelHandlerContext localCtx = session.getCtx();
if ((localCtx != null) && (localCtx.channel() != null) && (localCtx.channel().isOpen())
&& (localCtx.channel().isActive()) && (localCtx.channel().isWritable())) {
if(session.getChannel().isClosed()&&session.getChannel().isConnected()){
// ChannelHandlerContext localCtx = session.getCtx();
// if ((localCtx != null) && (localCtx.channel() != null) && (localCtx.channel().isOpen())
// && (localCtx.channel().isActive()) && (localCtx.channel().isWritable())) {
if(session.getFiveReady() == 1 && session.getFiveByteBuf()!=null){
session.putBackIndicationToMap(MessageTypeProto.MessageType.FIVE_PLAYER_REFLUSH_INDICATION_VALUE,session.getFiveByteBuf());
session.setFiveByteBuf(null);