Witam, piszę prosty serwer tcp na soketach używając biblioteki Qt. Do testów czy połączenie działa użyłem prostego skryptu napisanego w pythonie.. Wszystko jest ok tylko po połączeniu się klienta aplikacja wyłącza się po około sekundach. Próbowałem połączenia zakończeniu połączenia (metoda close) na obiekcie conn użyć delete, a potem ustawić go na nullptr, ale nic to nie dało. Kolejny problem pojawia się gdy po kliknięciu przycisku "serverFlowBtn" chcę aby jego tekst w zależności od tego czy serwer jest nasłuchuje pokazywał się jako Start albo Stop, ale tekst mogę zmienić tylko w konstruktorze klasy MainWindow inaczej aplikacja się wysypuje. Dlaczego tak jest i jak mam naprawić te dwa problemy?
kod serwera:
#include "mainwindow.h"
MainWindow::MainWindow()
{
this->resize(800, 600);
serverRunning = false;
mainLayout = new QVBoxLayout(this);
mainLayout->setSpacing(10);
mainLayout->setAlignment(Qt::AlignTop);
QTextEdit* logInfo = new QTextEdit(this);
logInfo->setReadOnly(true);
mainLayout->addWidget(logInfo);
QPushButton* serverFlowBtn = new QPushButton("Start", this);
serverFlowBtn->setMinimumHeight(40);
mainLayout->addWidget(serverFlowBtn);
QPushButton* clearLogsBtn = new QPushButton("Clear", this);
clearLogsBtn->setMinimumHeight(40);
mainLayout->addWidget(clearLogsBtn);
server = new QTcpServer(this);
QObject::connect(clearLogsBtn, &QPushButton::clicked, this, [logInfo]{logInfo->clear();});
QObject::connect(serverFlowBtn, &QPushButton::clicked, this, [this]{this->serverFlowBtnClicked();});
QObject::connect(server, &QTcpServer::newConnection, this, [this]{this->startNewConnection();});
this->show();
}
void MainWindow::startNewConnection()
{
qDebug() << "it works!";
conn = server->nextPendingConnection();
QByteArray responseMsg = "this is test message";
conn->write(responseMsg);
conn->waitForBytesWritten();
conn->waitForReadyRead();
QByteArray clientResponse = conn->readAll();
logInfo->setText(QString(clientResponse));
conn->close();
delete conn;
conn = nullptr;
//server->deleteLater();
// server->close();
}
void MainWindow::serverFlowBtnClicked()
{
if(serverRunning == false){
serverRunning = true;
this->serverFlowBtn->setText("Stop");
this->startListening();
}
else if(serverRunning == true){
serverRunning = false;
this->serverFlowBtn->setText("Start");
this->stopListening();
}
//qDebug() << serverRunning;
}
void MainWindow::startListening()
{
if(!server->listen(QHostAddress::LocalHost, 4444))
{
QMessageBox::critical(nullptr, "Error", "Failed to listen on port 4444", QMessageBox::Ok);
}
}
void MainWindow::stopListening()
{
server->close();
}
testowy skrypt w pythonie, który służy do połączenia
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind(('127.0.0.1', 5555)) # This command is optional
with s:
s.connect(('127.0.0.1', 4444))
s.send(b'Hello, world!!!')
data = s.recv(1024)
print("Recived: ", repr(data))