qt_demoe/nettool/api/tcpserver.cpp

83 lines
2.0 KiB
C++
Raw Normal View History

2019-09-29 05:13:01 +00:00
#include "tcpserver.h"
#include "quiwidget.h"
TcpServer::TcpServer(QObject *parent) : QTcpServer(parent)
{
connect(this, SIGNAL(newConnection()), this, SLOT(newConnection()));
2019-09-29 05:13:01 +00:00
}
void TcpServer::newConnection()
2019-09-29 05:13:01 +00:00
{
QTcpSocket *socket = this->nextPendingConnection();
TcpClient *client = new TcpClient(socket, this);
connect(client, SIGNAL(clientDisconnected()), this, SLOT(disconnected()));
2019-09-29 05:13:01 +00:00
connect(client, SIGNAL(sendData(QString, int, QString)), this, SIGNAL(sendData(QString, int, QString)));
connect(client, SIGNAL(receiveData(QString, int, QString)), this, SIGNAL(receiveData(QString, int, QString)));
QString ip = client->getIP();
int port = client->getPort();
2019-09-29 05:13:01 +00:00
emit clientConnected(ip, port);
emit sendData(ip, port, "客户端上线");
//连接后加入链表
clients.append(client);
}
void TcpServer::disconnected()
{
TcpClient *client = (TcpClient *)sender();
QString ip = client->getIP();
int port = client->getPort();
emit clientDisconnected(ip, port);
emit sendData(ip, port, "客户端下线");
//断开连接后从链表中移除
clients.removeOne(client);
}
bool TcpServer::start()
{
2019-12-05 08:01:43 +00:00
bool ok = listen(QHostAddress(App::TcpListenIP), App::TcpListenPort);
2019-09-29 05:13:01 +00:00
return ok;
}
void TcpServer::stop()
{
remove();
this->close();
}
void TcpServer::writeData(const QString &ip, int port, const QString &data)
{
foreach (TcpClient *client, clients) {
if (client->getIP() == ip && client->getPort() == port) {
2019-09-29 05:13:01 +00:00
client->sendData(data);
break;
}
}
}
void TcpServer::writeData(const QString &data)
{
foreach (TcpClient *client, clients) {
client->sendData(data);
}
}
void TcpServer::remove(const QString &ip, int port)
{
foreach (TcpClient *client, clients) {
if (client->getIP() == ip && client->getPort() == port) {
client->abort();
2019-09-29 05:13:01 +00:00
break;
}
}
}
void TcpServer::remove()
{
foreach (TcpClient *client, clients) {
client->abort();
2019-09-29 05:13:01 +00:00
}
}