qt_host/mainwindow.cpp

70 lines
1.8 KiB
C++
Raw Permalink Normal View History

2024-09-08 23:27:43 +00:00
#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);
2024-09-09 01:54:17 +00:00
str = "收到数据:" + str;
// std::cout << str.toStdString() << std::endl;
QByteArray data1 = str.toUtf8();
socket->write(data1);
2024-09-08 23:27:43 +00:00
}