wfview/tcpserver.cpp

99 wiersze
2.4 KiB
C++
Czysty Zwykły widok Historia

2022-03-23 10:12:42 +00:00
#include "tcpserver.h"
#include "logcategories.h"
tcpServer::tcpServer(QObject* parent) : QTcpServer(parent)
2022-03-23 10:12:42 +00:00
{
}
tcpServer::~tcpServer()
{
qInfo(logTcpServer()) << "closing tcpServer";
}
int tcpServer::startServer(qint16 port) {
if (!this->listen(QHostAddress::Any, port)) {
qInfo(logTcpServer()) << "could not start on port " << port;
return -1;
2022-03-23 10:12:42 +00:00
}
else
{
qInfo(logTcpServer()) << "started on port " << port;
2022-03-23 10:12:42 +00:00
}
return 0;
2022-03-23 10:12:42 +00:00
}
void tcpServer::incomingConnection(qintptr socket) {
tcpServerClient* client = new tcpServerClient(socket, this);
connect(this, SIGNAL(onStopped()), client, SLOT(closeSocket()));
2022-04-03 19:16:52 +00:00
emit newClient(socket); // Signal par
}
void tcpServer::stopServer()
2022-03-23 10:12:42 +00:00
{
qInfo(logTcpServer()) << "stopping server";
emit onStopped();
}
void tcpServer::receiveDataFromClient(QByteArray data)
{
2022-04-03 19:16:52 +00:00
emit receiveData(data);
}
void tcpServer::sendData(QByteArray data) {
emit sendDataToClient(data);
2022-03-23 10:12:42 +00:00
}
tcpServerClient::tcpServerClient(int socketId, tcpServer* parent) : QObject(parent)
2022-03-23 10:12:42 +00:00
{
sessionId = socketId;
socket = new QTcpSocket(this);
this->parent = parent;
if (!socket->setSocketDescriptor(sessionId))
{
qInfo(logTcpServer()) << " error binding socket: " << sessionId;
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()), Qt::DirectConnection);
connect(parent, SIGNAL(sendDataToClient(QByteArray)), this, SLOT(receiveDataToClient(QByteArray)), Qt::DirectConnection);
connect(this, SIGNAL(sendDataFromClient(QByteArray)), parent, SLOT(receiveDataFromClient(QByteArray)), Qt::DirectConnection);
qInfo(logTcpServer()) << " session connected: " << sessionId;
2022-03-23 10:12:42 +00:00
}
void tcpServerClient::socketReadyRead() {
2022-03-23 10:12:42 +00:00
QByteArray data;
if (socket->bytesAvailable()) {
data=socket->readAll();
emit sendDataFromClient(data);
2022-03-23 10:12:42 +00:00
}
}
2022-03-23 10:12:42 +00:00
void tcpServerClient::socketDisconnected() {
qInfo(logTcpServer()) << sessionId << "disconnected";
socket->deleteLater();
this->deleteLater();
2022-03-23 10:12:42 +00:00
}
void tcpServerClient::closeSocket()
{
socket->close();
}
2022-03-23 10:12:42 +00:00
void tcpServerClient::receiveDataToClient(QByteArray data) {
2022-03-23 10:12:42 +00:00
if (socket != Q_NULLPTR && socket->isValid() && socket->isOpen())
{
2022-03-23 10:12:42 +00:00
socket->write(data);
}
else
{
qInfo(logTcpServer()) << "socket not open!";
2022-03-23 10:12:42 +00:00
}
}