diff --git a/MarioDungeonServer/MysqlServer.cpp b/MarioDungeonServer/MysqlServer.cpp index e4622c9..50be174 100755 --- a/MarioDungeonServer/MysqlServer.cpp +++ b/MarioDungeonServer/MysqlServer.cpp @@ -8,32 +8,60 @@ int MysqlServer::connect() LOG_ERROR<<"mysql init falied"; return -1; } - - mysql = mysql_real_connect(mysql,SERVER_IP, "root", "140226", "MarioDungeon", 0, NULL, 0);//连接到数据库 + if(real_connect()) + { + LOG_ERROR<<"mysql real_connect falied"; + return -1; + } + + return 0; +} +int MysqlServer::real_connect() +{ + mysql = mysql_real_connect(mysql,SERVER_IP, "root", "140226", "MarioDungeon", 0, NULL, 0);//连接到数据库 if(mysql) { LOG_INFO<<"MySQL connection success"; + int res=mysql_query(mysql, "set names utf8");//设置查询字符集为utf8 + if(res!=0) + { + LOG_INFO<<"mysql_query set utf8 error"; + return -1; + } + else + LOG_INFO<<"MySQL set utf8 success"; } else { LOG_WARN<<" MySQL connection failed"; return -1; } - return 0; + return 0; } int MysqlServer::sqlQuery(const char *query) { - int res=mysql_query(mysql, "set names utf8");//设置查询字符集为utf8 - if(res!=0) - { - LOG_INFO<<"mysql_query set utf8 error"; - return -1; - } - res=mysql_query(mysql,query); + int res=mysql_query(mysql,query); if(res) { - return -1; + int flag=mysql_errno(mysql); + if(flag==CR_SERVER_LOST) + { + if(real_connect()) + { + LOG_ERROR<<"retry real_connect falied"; + return -1; + } + else + { + LOG_INFO<<"retry real_connect success"; + res=mysql_query(mysql,query); + if(res) + return -1; + } + } + else + return -1; } return 0; } diff --git a/MarioDungeonServer/MysqlServer.h b/MarioDungeonServer/MysqlServer.h index 74bd39d..71078c2 100755 --- a/MarioDungeonServer/MysqlServer.h +++ b/MarioDungeonServer/MysqlServer.h @@ -7,6 +7,7 @@ #include #include #include "mysql/mysql.h" +#include "mysql/errmsg.h" #include "muduo/net/TcpServer.h" #include "muduo/net/TcpConnection.h" #include "muduo/base/Logging.h" @@ -24,6 +25,7 @@ class MysqlServer MysqlServer():mysql(nullptr),res_ptr(nullptr),sqlrow(0){} void brodcast(const string& msg); int connect(); + int real_connect(); int sqlQuery(const char *query); string Register(char* name,char* password); string Login(const TcpConnectionPtr& conn,char* name,char* password); diff --git a/MarioDungeonServer/restart.sh b/MarioDungeonServer/restart.sh new file mode 100644 index 0000000..a5d8d7e --- /dev/null +++ b/MarioDungeonServer/restart.sh @@ -0,0 +1,14 @@ +#! /bin/bash + +while true +do + monitor=`ps -ef | grep main | grep -v grep | wc -l ` + if [ $monitor -eq 0 ] ; + then + echo "MarioServer program is not running, restart it" + ./main 2021 + #else + #echo "MarioServer program is running" + fi + sleep 1 +done