This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cpp
94 lines (81 loc) · 2.2 KB
/
server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "server.h"
#include "ui_server.h"
Server::Server(QWidget *parent) :
QWidget(parent),
ui(new Ui::Server)
{
ui->setupUi(this);
command = new Command();
listenSocket = new QTcpServer(this);
QObject::connect(listenSocket, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}
Server::~Server()
{
delete ui;
}
void Server::initServer()
{
if (!listenSocket->listen()) {
close();
return;
}
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
if (ipAddress.isEmpty()) {
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
}
ui->IP->setText(tr("%1:%2").arg(ipAddress).arg(listenSocket->serverPort()));
}
void Server::acceptConnection()
{
emit enablePlay();
ui->notificationLabel->setText("Client connected!");
ui->doneButton->setEnabled(true);
readWriteSocket = listenSocket->nextPendingConnection();
QObject::connect(readWriteSocket, SIGNAL(readyRead()), this, SLOT(receiveData()));
QObject::connect(readWriteSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
void Server::receiveData()
{
QByteArray block = readWriteSocket->readAll();
QDataStream ds(&block, QIODevice::ReadOnly);
ds >> currentData;
if (currentData.mid(0, 4) != "!sta") {
command->parse(currentData);
} else {
emit theyReady();
}
}
void Server::disconnected()
{
ui->notificationLabel->setText("The client has disconnected!");
this->show();
emit stopGame();
}
void Server::sendData(QString data)
{
QByteArray block;
QDataStream ds(&block, QIODevice::WriteOnly);
ds << data;
readWriteSocket->write(block);
}
void Server::sendChessSeq(QList<int> &seq)
{
QString cmd = "!sta ";
for (int i = 0; i < seq.size(); i++) {
cmd += QString("%1").arg(seq[i]);
cmd += " ";
}
sendData(cmd);
}
void Server::on_doneButton_clicked()
{
this->hide();
}