qt_host/mainwindow.cpp

64 lines
1.7 KiB
C++

#include "mainwindow.h"
#include "./ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->le_port->setText("1234");
connect(ui->bt_start, &QPushButton::clicked, this, &MainWindow::start_server);
connect(ui->bt_stop, &QPushButton::clicked, this, &MainWindow::stop_server);
client = nullptr;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::start_server()
{
int port = ui->le_port->text().toInt();
if (port == 0)
{
return;
}
server.listen(QHostAddress::Any, port);
ui->lb_state->setText("启动成功");
ui->lb_listen_port->setText(QString::number(port));
connect(&server, &QTcpServer::newConnection, this, &MainWindow::new_connection);
}
void MainWindow::stop_server()
{
server.close();
ui->lb_state->setText("已停止");
ui->lb_listen_port->setText("");
}
void MainWindow::new_connection()
{
if (server.hasPendingConnections())
{
std::cout<< "new connection" << std::endl;
if (client == nullptr)
{
client = server.nextPendingConnection();
connect(client, &QTcpSocket::readyRead, this, &MainWindow::read_data);
ui->lb_client->setText("已连接");
connect(client, &QTcpSocket::disconnected, this, &MainWindow::disconnected);
}
}
}
void MainWindow::disconnected()
{
ui->lb_client->setText("已断开");
client = nullptr;
}
void MainWindow::read_data()
{
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
QByteArray data = socket->readAll();
QString str = data.data();
ui->pte_info->append(str);
}