qt_demoe/tool/nettool/api/tcpserver.cpp

76 lines
2.0 KiB
C++
Raw Normal View History

2019-09-29 05:13:01 +00:00
#include "tcpserver.h"
2021-06-08 11:02:49 +00:00
#include "quihelper.h"
2019-09-29 05:13:01 +00:00
TcpServer::TcpServer(QObject *parent) : QTcpServer(parent)
{
2021-08-22 02:57:02 +00:00
connect(this, SIGNAL(newConnection()), this, SLOT(slot_newConnection()));
2019-09-29 05:13:01 +00:00
}
2021-08-22 02:57:02 +00:00
void TcpServer::slot_newConnection()
2019-09-29 05:13:01 +00:00
{
QTcpSocket *socket = this->nextPendingConnection();
TcpClient *client = new TcpClient(socket, this);
2021-08-22 02:57:02 +00:00
connect(client, SIGNAL(disconnected(QString, int)), this, SLOT(slot_disconnected(QString, int)));
connect(client, SIGNAL(error(QString, int, QString)), this, SIGNAL(error(QString, int, QString)));
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)));
2021-08-22 02:57:02 +00:00
emit connected(client->getIP(), client->getPort());
2019-09-29 05:13:01 +00:00
//连接后加入链表
clients.append(client);
}
2021-08-22 02:57:02 +00:00
void TcpServer::slot_disconnected(const QString &ip, int port)
2019-09-29 05:13:01 +00:00
{
TcpClient *client = (TcpClient *)sender();
2021-08-22 02:57:02 +00:00
emit disconnected(ip, port);
2019-09-29 05:13:01 +00:00
//断开连接后从链表中移除
clients.removeOne(client);
}
bool TcpServer::start()
{
2021-04-13 01:36:22 +00:00
bool ok = listen(QHostAddress(AppConfig::TcpListenIP), AppConfig::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
}
}