120 lines
2.4 KiB
C++
120 lines
2.4 KiB
C++
#include "TcpSocket.hpp"
|
|
#include "NetConst.hpp"
|
|
#include "sql.hpp"
|
|
#include "values/DnaManager.hpp"
|
|
#include "checker.hpp"
|
|
|
|
#include <iostream>
|
|
#include <map>
|
|
#include <thread>
|
|
|
|
// use pthread rw_lock to lock db so you can safy clone .db file
|
|
|
|
// When a new client connected:
|
|
void call(int sock, sockaddr_in newSocketInfo)
|
|
{
|
|
std::string add = TcpSocket::remoteAddress(newSocketInfo);
|
|
printf("new: %s\n", add.c_str());
|
|
int64_t conf, id;
|
|
Message message;
|
|
|
|
TcpSocket::recvt(sock, &conf, sizeof(conf));
|
|
TcpSocket::recvt(sock, &id, sizeof(id));
|
|
|
|
if (conf != StartHeader)
|
|
{
|
|
printf("StartHeader ERROR\n");
|
|
TcpSocket::closet(sock);
|
|
return;
|
|
}
|
|
|
|
if (id == 0)
|
|
{
|
|
printf("ID ERROR\n");
|
|
TcpSocket::closet(sock);
|
|
return;
|
|
}
|
|
|
|
bool ok = true;
|
|
|
|
sqlite3 *db;
|
|
sqlite3_stmt *stmt;
|
|
|
|
int rc = sql::open(DB_NAME, &db);
|
|
if (rc)
|
|
{
|
|
fprintf(stderr, "Can't open database: %s\n", sql::errmsg(db));
|
|
ok = false;
|
|
}
|
|
|
|
sql::prepare_v2(db, max_gen, -1, &stmt, NULL);
|
|
sql::bind_int64(stmt, 1, id);
|
|
int64_t gen = 0;
|
|
while (sql::step(stmt) != SQL_DONE)
|
|
{
|
|
int num_cols = sql::column_count(stmt);
|
|
|
|
int type = sql::column_type(stmt, 0);
|
|
|
|
if (type == SQL_NULL)
|
|
break;
|
|
gen = sql::column_int64(stmt, 0);
|
|
gen++;
|
|
}
|
|
sql::finalize(stmt);
|
|
|
|
sql::prepare_v2(db, insert_data, -1, &stmt, NULL);
|
|
|
|
while (ok)
|
|
{
|
|
message.mess = Mess::REQ_SEND_GEN;
|
|
message.data = gen;
|
|
printf("requesting gen %ld\n", gen);
|
|
TcpSocket::sendt(sock, &message, sizeof(Message));
|
|
TcpSocket::recvt(sock, &message, sizeof(Message));
|
|
|
|
if (message.mess == Mess::RES_NO)
|
|
{
|
|
break;
|
|
}
|
|
|
|
std::vector<NetUnit> list;
|
|
list.resize(NUM_PER_GEN);
|
|
|
|
TcpSocket::recvt(sock, list.data(), NUM_PER_GEN * sizeof(NetUnit));
|
|
|
|
for (size_t i = 0; i < list.size(); i++)
|
|
{
|
|
sql::bind_int64(stmt, 1, id);
|
|
sql::bind_int64(stmt, 2, gen);
|
|
sql::bind_int64(stmt, 3, list[i].hash);
|
|
sql::bind_int64(stmt, 4, list[i].index);
|
|
sql::bind_int64(stmt, 5, list[i].liked);
|
|
sql::step(stmt);
|
|
sql::reset(stmt);
|
|
}
|
|
|
|
gen++;
|
|
}
|
|
|
|
sql::finalize(stmt);
|
|
|
|
sql::close(db);
|
|
printf("del\n");
|
|
TcpSocket::closet(sock);
|
|
}
|
|
|
|
int main()
|
|
{
|
|
sql::init();
|
|
std::thread t(checker);
|
|
// Bind the server to a port.
|
|
int err = TcpSocket::listent("0.0.0.0", 8888, call);
|
|
if (err < 0)
|
|
{
|
|
printf("ERROR %d", err);
|
|
return 0;
|
|
}
|
|
|
|
return 0;
|
|
} |