天堂2使用国外开源游戏引擎L2JGameServer作为服务端游戏引擎,最近几天看了一下其源码,在此分享个人的经验。其主类为L2LoginServer:
我们就从它的构造函数开始吧:
//读取日志配置文件,配置日志
InputStream is = null;
try
{
is = new FileInputStream(new File(LOG_NAME));
LogManager.getLogManager().readConfiguration(is);
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//读取其他游戏配置信息,如服务器灾难预防配置,数据库连接信息等,游戏技能等
Config.load();
//初始化mysql数据库连接
try
{
L2DatabaseFactory.getInstance();
}
catch (SQLException e)
{
_log.log(Level.SEVERE, "FATAL: Failed initializing database. Reason: " + e.getMessage(), e);
System.exit(1);
}
这个一看就知道,我就不用说了:
try
{
LoginController.load();
}
catch (GeneralSecurityException e)
{
_log.log(Level.SEVERE, "FATAL: Failed initializing LoginController. Reason: " + e.getMessage(), e);
System.exit(1);
}
/**生成RSA加密解密密钥在通信过程使用
:生成密钥对,发送信息之前加密,收到信息时候解密
private LoginController() throws GeneralSecurityException
{
_log.info("Loading LoginController...");
_hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();
_keyPairs = new ScrambledKeyPair[10];
KeyPairGenerator keygen = null;
keygen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
keygen.initialize(spec);
//generate the initial set of keys
for (int i = 0; i < 10; i++)
{
_keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
}
_log.info("Cached 10 KeyPairs for RSA communication");
testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate());
// Store keys for blowfish communication
generateBlowFishKeys();
_purge = new PurgeThread();
_purge.setDaemon(true);
_purge.start();
}
try
{
GameServerTable.load();
}
catch (GeneralSecurityException e)
{
_log.log(Level.SEVERE, "FATAL: Failed to load GameServerTable. Reason: " + e.getMessage(), e);
System.exit(1);
}
//读取服务器信息以及生成RSA密钥
public GameServerTable() throws SQLException, NoSuchAlgorithmException, InvalidAlgorithmParameterException
{
loadServerNames();
_log.info("Loaded " + _serverNames.size() + " server names");
loadRegisteredGameServers();
_log.info("Loaded " + _gameServerTable.size() + " registered Game Servers");
loadRSAKeys();
_log.info("Cached " + _keyPairs.length + " RSA keys for Game Server communication.");
}
//服务器收到信息时候使用私钥解密,发送数据时候私钥加密
//客户端使用公钥解密收到数据,使用公钥加密要发送数据
private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
keyGen.initialize(spec);
//生成10个KeyPair,发送数据时候随机选择一个私钥加密
_keyPairs = new KeyPair[KEYS_SIZE];
for (int i = 0; i < KEYS_SIZE; i++)
{
_keyPairs[i] = keyGen.genKeyPair();
}
}
//加载配置的禁止访问IP
loadBanFile();