-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomunication.cpp
111 lines (94 loc) · 2.64 KB
/
comunication.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "comunication.h"
Comunication::Comunication(Board *b) : connected(false), server(0), client(0)
{
board = b;
}
void Comunication::createConnection(bool isServer, QString ip)
{
if (connected)
{
int answer = QMessageBox::question(board, tr("Chess Connection"), tr("start a new connection?"),
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::No)
return;
close();
}
if (isServer)
{
server = new QTcpServer(this);
if (!server->listen(QHostAddress::Any, 5170)) {
QMessageBox::information(board, tr("Chess Server"),
tr("Unable to start the server: %1.")
.arg(server->errorString()));
close();
return;
}
connect(server, SIGNAL(newConnection()), this, SLOT(handleConnection()));
}
else
{
client = new QTcpSocket(this);
client->connectToHost(ip, 5170);
setClient(client);
}
connected = true;
}
void Comunication::sendMessage(const QString msg)
{
QByteArray barr;
barr.append(msg);
client->write(barr);
client->flush();
}
void Comunication::handleConnection()
{
if (!client) {
setClient(server->nextPendingConnection());
board->mode(HUMAN_ONLINE);
board->restart();
} else {
server->nextPendingConnection()->close();
}
}
void Comunication::readClient()
{
if (client && client->canReadLine())
{
QString data = client->readLine();
emit receiveMessage(data);
}
}
void Comunication::setClient(QTcpSocket *c)
{
client = c;
connect(client, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnect()));
connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
void Comunication::close()
{
if (server && server->isListening())
server->close();
if (client && client->isOpen())
client->abort();
server = 0;
client = 0;
connected = false;
board->mode(UNSTARTED);
}
void Comunication::clientDisconnect()
{
QMessageBox::information(board, tr("Chess connection"),
tr("Connection lose."));
close();
}
void Comunication::displayError(QAbstractSocket::SocketError error)
{
switch (error) {
default:
QMessageBox::information(board, tr("Chess connection"),
tr("The following error occurred: %1.")
.arg(client->errorString()));
}
close();
}