文章目录
前言
本篇记录QT中TCP和UDP网络编程知识。
一、QT中的TCP编程
1. TCP简介
- TCP是面向连接的、可靠的、基于字节流的传输层通信协议。
- TCP的服务端和客户端通信首先必须建立连接。
- 建立连接方式:服务端监听某个端口,当有客户端通过ip和port连接时,就会创建一个socket连接,之后就可以互发数据了。
- QT中将socket视为输入输出流,数据的收发是通过read()和write()来进行,而不是常见的send和recv。
----------------------------接下来,我们以一个实例来解析服务端和用户端程序编写-------------------------
2. 服务端程序编写
2.1 编写步骤:
【1】配置:①pro文件中添加network;②添加头文件<QTcpServer>和<QTcpSocket>。
【2】创建服务端对象:QTcpServer *tcpServer;(具体分配空间在构造函数中)
【3】服务端-客户端的信号槽连接:connect(tcpServer, SIGNAL(newConnection()), this, SLOT(mNewConnection()));
【4】编写【3】中的槽函数mNewConnection():
- ①获取客户端对象:QTcpSocket *tmpTcpSocket = tcpServer->nextPendingConnection();
- ②获取客户端信息:
- 获取客户端ip:tmpTcpSocket->peerAddress().toString();
- 获取客户端port:tmpTcpSocket->peerPort();
- ③创建信号槽来处理客户端的连接状态:connect(tmpTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(mStateChanged(QAbstractSocket::SocketState)));
- ④创建信号槽来接收客户端发送的信息:connect(tmpTcpSocket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
【5】编写【4】中的槽函数mStateChanged(...):用switch-case结构来处理连接状态,当状态为断开连接时,删除当前调用的客户端对象。
【6】编写【4】中的槽函数receiveMessage():调用tmpTcpSocket->readAll()来获取客户端发送的信息。
【7】创建函数来给客户端发送数据:内部调用"客户端对象.write("写入的内容")"。
【8】开始监听:调用tcpServer->listen(QHostAddress("192.168.124.151"), 9999); 监听ip为192.168.124.151,port为9999。
2.2 编写代码:
【1】widget.h:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QTcpServer> #include <QTcpSocket> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); private slots: void mNewConnection(); void receiveMessage(); void mStateChanged(QAbstractSocket::SocketState socketState); void on_pushButton_3_clicked(); void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::Widget *ui; QTcpServer *tcpServer; }; #endif // WIDGET_H
【2】widget.cpp:
#include "widget.h" #include "ui_widget.h" /*********************************************************** * @函数名:Widget * @功 能:构造函数---创建服务端对象,与客户端连接 * @参 数:parent---父对象 * @返回值:无 *********************************************************/ Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); this->setWindowTitle("服务端"); //创建对象,与客户端连接 tcpServer = new QTcpServer(this); connect(tcpServer, SIGNAL(newConnection()), this, SLOT(mNewConnection())); } /***