include Network Network Network unsigned int port this- _server new QT

 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
#include "Network.h"
Network::Network(unsigned int port) {
this->_server = new QTcpServer(this);
connect(this->_server, SIGNAL(newConnection()), this, SLOT(newUser()));
if (!this->_server->listen(QHostAddress::Any, port)) {
qDebug() << "Unable to start the server: " << this->_server->errorString();
} else {
qDebug() << "Listen port: " << port;
}
this->_socket = new QList<QTcpSocket *>;
}
Network::~Network()
{
foreach (QTcpSocket *socketReceiver, *this->_socket) {
socketReceiver->close();
}
}
void Network::newUser() {
qDebug() << "New connection";
while (QTcpSocket * socket = this->_server->nextPendingConnection()) {
this->_socket->push_back(socket);
connect(socket, SIGNAL(readyRead()), this, SLOT(readUserData()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedClient()));
}
}
void Network::readUserData() {
QTcpSocket *socket = (QTcpSocket *)this->sender();
QByteArray data = socket->readAll();
QByteArray width_str(4, '0');
QByteArray tmp_byte_arr = QByteArray::number(socket->socketDescriptor(), 16);
width_str.replace(4 - tmp_byte_arr.size(), tmp_byte_arr.size(), tmp_byte_arr);
data.prepend(width_str);
foreach (QTcpSocket *socketReceiver, *this->_socket) {
if (socketReceiver->socketDescriptor() != socket->socketDescriptor()) {
socketReceiver->write(data);
}
}
}
void Network::disconnectedClient()
{
qDebug() << "Connection lost";
QTcpSocket *socket = (QTcpSocket *)this->sender();
int index = this->_socket->indexOf(socket);
this->_socket->removeAt(index);
}