收获总结:
-
通过这个项目,我掌握了Qt的Tcp服务器类QTcpServer和Tcp套接字类QTcpSocket的使用。
-
从读取数据的槽函数调用read() 或 readAll() 读取数据,以及发送按钮的函数调用tcpSocket->write()中,我进一步理解了套接字这个概念。
-
还练习了Qt ui布局。
-
还进一步掌握了做gif图演示效果。
项目目标:
熟悉QT网络编程中TCP编程
技术栈与环境:
开发语言: C++ GUI框架: Qt 6.9.0 开发环境: Qt Creator 16.0.1
编译器: MinGW 64-bit 系统平台:Windows 11
最终效果展示:


功能描述:
一个服务器窗口,一个客户端窗口,互相发送消息。^_^
UI布局:


实现:
需要使用到Qt的网络模块:

需要使用的库:
#include <QTcpServer>
#include <QTcpSocket>
窗体类增加成员:
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
需要使用的类的方法:
Server:
1、QTcpServer的方法QTcpServer():new一个实例
2、QTcpSocket的方法QTcpSocket():new一个实例
3、newConnection: newConnection()信号是QTcpServer类内置的信号。当服务器监听到新的客户端连接请求时,会自动触发此信号。
4、readyRead: 这是 QTcpSocket 的内置信号,当套接字接收到新的数据时自动触发。
5、listen: Call listen() to have the server listen for incoming connections. The newConnection() signal is then emitted each time a client connects to the server.
bool QTcpServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0)
Tells the server to listen for incoming connections on address address and port port. If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces.
Returns true on success; otherwise returns false.
6、tcpServer->close():
void QTcpServer::close()
Closes the server. The server will no longer listen for incoming connections.
7、tcpSocket->write():

8、connectToHost:

功能实现方法:
Server端:点击打开按钮,开始监听,使用lisetn从指定端口(输入的)监听任意主机;当服务器监听到新的客户端连接请求时,会自动触发newConnection信号,将tcpServer的此信号和自定义的连接槽函数绑定;在自定义的槽函数将QTcpSocket的readyRead信号和自定义的读取槽函数绑定;在自定义的读取槽函数中读取套接字的数据,显示到ui上;关闭按钮:关服务器;发送按钮:往套接字里写数据。
cpp
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
tcpSocket = new QTcpSocket(this);
//QTcpSocket 类的实例,表示一个TCP套接字,通常用于客户端或服务器与客户端的通信
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection_Slot()));
//关联tcpServer发出的newConnection()信号和this(此Widget实例)下自定义的newConnection_Slot()槽函数
//newConnection()信号是QTcpServer类内置的信号。当服务器监听到新的客户端连接请求时,会自动触发此信号。
}
Widget::~Widget()
{
delete ui;
}
void Widget::newConnection_Slot()
{
tcpSocket = tcpServer->nextPendingConnection(); //获得已经连接的客户端的Socket信息
connect(tcpSocket, &QTcpSocket::readyRead, this, &Widget::readyRead_Slot);
//readyRead: 这是 QTcpSocket 的内置信号,当套接字接收到新的数据时自动触发。
//触发条件:操作系统内核的套接字接收缓冲区中有数据可读(例如对方发送了数据,或网络传输的数据到达本地)。
//当网络数据到达套接字时,Qt的事件循环会检测到可读事件,并触发 readyRead() 信号。
//通过信号与槽机制,自动调用 readyRead_Slot() 槽函数,实现异步、非阻塞的数据处理。
}
Client:类似,更简单。因为不用使用QTcpServer类。
可优化点:
搞搞多客户端的。^_^