#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent) // 初始化基类,指定父窗口
, ui(new Ui::Widget) // 初始化用户界面
{
ui->setupUi(this); // 根据ui设计文件设置界面
// 创建TCP服务器实例,隶属于当前Widget,便于管理资源
tcpServer = new QTcpServer(this);
// 尝试让服务器监听任意IP地址的8888端口
if (!tcpServer->listen(QHostAddress::Any, 8888)) {
qDebug() << "服务器启动失败。";
return ; // 启动失败则退出构造函数
}
// 当有新连接到达时,触发处理新连接的槽函数
connect(tcpServer, &QTcpServer::newConnection, this, &Widget::handleNewConnection);
}
Widget::~Widget()
{
// 关闭TCP服务器,释放资源
tcpServer->close();
delete ui; // 释放界面资源
}
// 处理新连接的槽函数
void Widget::handleNewConnection()
{
// 检查是否有待处理的新连接
if (tcpServer->hasPendingConnections()) {
// 获取下一个待处理的连接,并将其赋值给成员变量
tcpSocket = tcpServer->nextPendingConnection();
// 当有数据可读时,更新显示区域的文本
connect(tcpSocket, &QTcpSocket::readyRead, this, [=]() {
ui->textEditRead->setText(tcpSocket->readAll());
});
}
}
// 槽函数:处理“发送”按钮点击事件
void Widget::on_btnWrite_clicked()
{
// 检查TCP套接字是否已连接且状态正常
if (tcpSocket && tcpSocket->state() == QAbstractSocket::ConnectedState) {
// 将输入框中的文本转换为UTF-8编码并发送
tcpSocket->write(ui->textEditWrite->toPlainText().toUtf8());
}
else {
qDebug() << "套接字未连接!";
}
}
10-project-tcpServer
最新推荐文章于 2024-07-21 12:51:42 发布