package be.demmel.jgws;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.AttributeKey;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.demmel.jgws.network.DefaultChannelInitializer;
import be.demmel.jgws.network.InboundPacketHandler;
import be.demmel.jgws.packets.Packet;
import be.demmel.jgws.packets.gameserver.outbound.P001_Ping;
import be.demmel.jgws.packets.serialization.PacketDeserializer;
import be.demmel.jgws.packets.serialization.PacketSerializer;
public class GameServerChannelInitializer extends DefaultChannelInitializer<GameServerSession> {
private static final Logger LOGGER = LoggerFactory.getLogger(GameServerChannelInitializer.class);
public GameServerChannelInitializer(Map<Integer, PacketDeserializer> packetDeserializers, InboundPacketHandler inboundPacketHandlerChooser,
Map<Class<? extends Packet>, PacketSerializer> packetSerializers, AttributeKey<GameServerSession> dataKey, Set<Class<? extends Packet>> inboundPacketsLogBlackList,
Set<Class<? extends Packet>> outboundPacketsLogBlackList) {
super(packetDeserializers, inboundPacketHandlerChooser, packetSerializers, dataKey, inboundPacketsLogBlackList, outboundPacketsLogBlackList);
}
public GameServerChannelInitializer(Map<Integer, PacketDeserializer> packetDeserializers, InboundPacketHandler inboundPacketHandlerChooser,
Map<Class<? extends Packet>, PacketSerializer> packetSerializers, AttributeKey<GameServerSession> dataKey) {
super(packetDeserializers, inboundPacketHandlerChooser, packetSerializers, dataKey);
}
@Override
public void initChannel(final SocketChannel ch) throws Exception {
super.initChannel(ch);
ch.eventLoop().scheduleAtFixedRate(() -> { // start sending pings to this client
GameServerSession playerData = ch.attr(SessionKey.SESSION_KEY).get();
// Retrieve the Character the player is currently playing
CharacterData character = playerData.getCurrentCharacter();
if (character.getPlayer() != PlayStatus.READY_TO_PLAY) {
return;
}
// Even if we sleep 250 ms we need to calcaulate this. Why? I dunno.
// FIXME: last ping time and heartbeat should not be stored in the character data...
long timeBetweenNowAndLastPing = new Date().getTime() - character.getLastPingTime().getTime();
LOGGER.debug("{} Sending Ping to account with account ID: {}", ch, playerData.getAccId());
P001_Ping ping = new P001_Ping();
ch.write(ping);
character.setLastPingTime(new Date());
}, 5000, 5000, TimeUnit.MILLISECONDS);
}
@Override
protected GameServerSession getServerDataInstance() {
return new GameServerSession();
}
}