tcpserver.cpp
2.84 KB
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
112
113
114
115
116
117
118
119
#include "tcpserver.h"
#include "qhostaddress.h"
TcpClient::TcpClient(int clientID, QObject *parent) :
QTcpSocket(parent)
{
this->clientID = clientID;
connect(this, SIGNAL(readyRead()), this, SLOT(readData()));
connect(this, SIGNAL(disconnected()), this, SLOT(disConnect()));
}
void TcpClient::readData()
{
if (bytesAvailable() <= 0) {
return;
}
QByteArray data = readAll();
emit clientReadData(clientID, peerAddress().toString(), peerPort(), data);
}
void TcpClient::disConnect()
{
emit clientDisConnect(clientID, peerAddress().toString(), peerPort());
}
TcpServer::TcpServer(QObject *parent) :
QTcpServer(parent)
{
clientCount = 0;
}
void TcpServer::incomingConnection(int handle)
{
TcpClient *client = new TcpClient(handle, this);
client->setSocketDescriptor(handle);
connect(client, SIGNAL(clientReadData(int, QString, int, QByteArray)),
this, SIGNAL(clientReadData(int, QString, int, QByteArray)));
connect(client, SIGNAL(clientDisConnect(int, QString, int)),
this, SLOT(disConnect(int, QString, int)));
QString ip = client->peerAddress().toString();
int port = client->peerPort();
clientLists.append(client);
clientIDs.append(handle);
clientInfo.append(QString("%1:%2").arg(ip).arg(port));
clientCount++;
emit clientConnect(handle, ip, port);
}
void TcpServer::disConnect(int clientID, QString ip, int port)
{
for (int i = 0; i < clientCount; i++) {
if (clientIDs.at(i) == clientID) {
clientLists.at(i)->close();
clientLists.removeAt(i);
clientIDs.removeAt(i);
clientInfo.removeAt(i);
clientCount--;
emit clientDisConnect(clientID, ip, port);
break;
}
}
}
void TcpServer::sendData(QString ip, int port, QByteArray data)
{
for (int i = 0; i < clientCount; i++) {
QString str = QString("::ffff:%1:%2").arg(ip).arg(port);
//qDebug() <<clientInfo.at(i);
if (str == clientInfo.at(i)) {
clientLists.at(i)->write(data);
break;
}
}
}
void TcpServer::sendData(QByteArray data)
{
for (int i = 0; i < clientCount; i++) {
clientLists.at(i)->write(data);
}
}
void TcpServer::closeAll()
{
foreach (TcpClient *client, clientLists) {
client->close();
}
this->close();
}
void TcpServer::closeAt(int i)
{
if(i < 0)
return;
if(i < clientLists.length())
clientLists[i]->close();
//this->close();
}
void TcpServer::closeClient(QString ip, int port)
{
for (int i = 0; i < clientCount; i++)
{
QString str = QString("::ffff:%1:%2").arg(ip).arg(port);
//qDebug() <<clientInfo.at(i);
if (str == clientInfo.at(i))
{
clientLists.at(i)->close();
break;
}
}
//this->close();
}