CodeLibrary/05_QtCreator_Cplus_TCPServer_20240423/widget.cpp

65 lines
2.0 KiB
C++
Raw Normal View History

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// 初始化构造函数
server = new QTcpServer;
// 监听指定的网卡和端口
// QHostAddress::AnyIPv4 -> 任意 IPV4 地址
// PORT 8000 端口
2024-04-24 23:08:17 +08:00
server->listen(QHostAddress(Local_IP), PORT);
2024-04-24 23:08:17 +08:00
ui->Message_Edit->insertPlainText("Message: Local Server " + Local_IP + " is open");
// 判断是否有客户端发起连接
// 如果有客户端发起连接 调用 newClientHandler 函数接收连接
connect(server, &QTcpServer::newConnection, this, &Widget::newClientHandler);
}
Widget::~Widget()
{
delete ui;
}
// 连接成功后执行的槽函数
void Widget::newClientHandler(){
// 建立 TCP 连接
QTcpSocket *socket = server->nextPendingConnection();
// 返回显示客户端的地址和端口号
// socket->peerAddress().toString() 获取客户端地址 QHostAddress 并转换到 QString
// QString::number(socket->peerPort()) 获取客户端端口号 Quint16 并转换到 QString
ui->IP_Edit->setText(socket->peerAddress().toString());
ui->Port_Edit->setText(QString::number(socket->peerPort()));
2024-04-24 23:08:17 +08:00
ui->Message_Edit->insertPlainText("\nConnect to: " + socket->peerAddress().toString());
// 是否有接收到消息
connect(socket, &QTcpSocket::readyRead, this, &Widget::clientInfoSlot);
}
// 客户端收到消息
void Widget::clientInfoSlot(){
// 获取信号的发出者
QTcpSocket *s = (QTcpSocket *)sender();
// 获取系统时间
QDateTime curremt_date = QDateTime::currentDateTime();
// 获取客户端地址
QString client_ip = s->peerAddress().toString();
// 读取信息并显示
ui->Message_Edit->insertPlainText("\nMessage for " + client_ip + " in " + curremt_date.toString("yyyy-MM-dd hh:mm:ss")
+ "\n-> " + QString(s->readAll()));
}
void Widget::on_ClearButton_clicked()
{
ui->Message_Edit->clear();
}