目录
1. TCP通信概述
TCP是一种被大多数Internet网络协议(如HTTP)用于数据传输的低级网络协议,它是可靠的、面向流、面向连接的传输协议,特别适合于连续数据传输。
TCP通信必须先建立TCP连接,分为服务器端和客户端。
Qt提供QTcpServer类和QTcpSocket类用于建立TCP通信。
服务器端必须使用QTcpServer用于端口监听,建立服务器;QTcpSocket用于建立连接后使用套接字进行通信。
2. QTcpServer
QTcpServer继承于QObject
2.1 公共函数
void close() 关闭服务器,停止网络监听
bool listen(address, port) 在给定IP地址和端口上开始监听,若成功返回true。address = QHostAddress addr(IP)
bool isListening() 返回true表示服务器处于监听状态
QTcpSocket* nextPendingConnection() 返回下一个等待接入的连接。套接字是作为服务器的子节点创建的,这意味着当QTcpServer对象被销毁时,它将被自动删除。在使用完对象后显式地删除它,以避免浪费内存。如果在没有挂起连接时调用此函数,则返回0。注意:返回的QTcpSocket对象不能从其他线程使用。如果您想使用来自另一个线程的传入连接,则需要重写incomingConnection()。
QHostAddress serverAddress() 若服务器处于监听状态,返回服务器地址
quint16 serverPort() 若服务器处于监听状态,返回服务器监听端口
bool waitForNewConnection() 以阻塞的方式等待新的连接
2.2 信号
void acceptError(QAbstractSocket::SocketError socketError) 当接受一个新的连接发生错误时发射此信号,参数socketError描述了错误信息
void newConnection() 当有新的连接时发射此信号
2.3 保护函数
void incomingConnection(qintptr socketDescriptor) 当有新的连接可用时,QTcpServer内部调用此函数,创建一个QTcpServer对象,添加到内部可用新连接列表,然后发射newConnection()信号。用户若从QTcpServer继承定义类,可以重定义此函数,但必须调用addPendingConnection()。qintptr根据系统类型不同而不同,32位为qint32,64位为qint64。
void addPendingConnection(QTcpSocket* socket) 由incomingConnection()调用,将创建的QTcpSocket添加到内部新可用连接列表。
3. QTcpSocket
QTcpSocket是从QIODevice间接继承的
QIODevice -> QAbstractSocket -> QTcpSocket
QTcpSocket类除了构造和析构,其他函数都是从QAbstractSocket继承或重定义的
3.1 公共函数
void connectToHost(QHostAddress& address, quint16 port) 以异步方式连接到指定IP地址和端口的TCP服务器,连接成功会发送connected()信号
void disconnectFromHost() 断开socket,关闭成功后会发射disconnected()信号
bool waitForConnected() 等待直到建立socket连接
bool waitForDisconnected() 等待直到断开socket连接
QHostAddress localAddress() 返回本socket的地址
quint16 localPort 返回本socket的端口
QHostAddress peerAddress() 在已连接状态下,返回对方socket的地址
QString peerName() 返回connectToHost()连接到的对方的主机名
quint16 peerPort() 在已连接状态下,返回对方socket的端口
qint64 readBufferSize() 返回内部读取缓冲区的大小,该大小决定了read()和realAll()函数能读出的数据的大小
void setReadBufferSize(qint64 size) 设置内部读取缓冲区的大小
qint64 bytesAvailable() 返回需要读取的缓冲区的数据的字节数
bool canReadLine() 如果有行数据要从socket缓冲区读取,则返回true
SocketState state() 返回socket当前的状态
3.2 信号
void connected() connectToHost()成功连接到服务器后会发射此信号
void disconnected() 断开socket连接后会发射此信号
void error(QAbstractSocket::SocketError socketError) 当socket发生错误时会发射此信号
void hostFound() 调用connectToHost()找到主机后会发射此信号
void stateChanged(QAbstractSocket::SocketState socketState) 当socket状态发生变化时会发射此信号,参数socketState表示socket当前的状态
void readyRead() 当缓冲区有新数据需要读取时会发射此信号,在此信号的槽函数里读取缓冲区的数据
4. 代码示例
4.1 服务器端
使用Qt网络模块,需要在配置文件.pro中添加:
Qt += network
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QAction>
#include <QCloseEvent>
#include <QComboBox>
#include <QGridLayout>
#include <QHostInfo>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTcpServer>
#include <QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
protected:
void closeEvent(QCloseEvent* event);
private slots:
//工具栏按钮
void slotActStartTriggered();
void slotActStopTriggered();
void slotActClearTriggered();
void slotActQuitTriggered();
//界面按钮
void slotBtnSendClicked();
//自定义槽函数
void slotNewConnection(); // QTcpServer的newConnection()信号
void slotClientConnected(); //客户端socket连接
void slotClientDisconnected(); //客户端socket断开连接
void slotSocketStateChange(QAbstractSocket::SocketState socketState);
void slotSocketReadyRead(); //读取socket传入的数据
private:
Ui::MainWindow* ui;
QAction* m_pActStartListen;
QAction* m_pActStopListen;
QAction* m_pActClearText;
QAction* m_pActQuit;
QWidget* m_pCentralWidget;
QGridLayout* m_pGridLayout;
QLabel* m_pLabel1;
QComboBox* m_pComBoxIP;
QLabel* m_pLabel2;
QSpinBox* m_pSpinBoxPort;
QLineEdit* m_pLineEdit;
QPushButton* m_pBtnSend;
QPlainTextEdit* m_pPlainText;
QLabel* m_pLabListenStatus; //状态栏标签
QLabel* m_pLabSocketState; //状态栏标签
QTcpServer* m_pTcpServer; // TCP服务器
QTcpSocket* m_pTcpSocket; // TCP通信的socket
QString getLocalIP(); //获取本机IP地址
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
this->setWindowTitle(QStringLiteral("TCP服务端"));
ui->menuBar->hide();
//工具栏
ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //设置工具栏显示风格(图标在上文字在下)
m_pActStartListen = new QAction(QIcon(":/new/prefix1/res/开始.png"), QStringLiteral("开始监听"), this);
m_pActStopListen = new QAction(QIcon(":/new/prefix1/res/暂停.png"), QStringLiteral("停止监听"), this);
m_pActClearText = new QAction(QIcon(":/new/prefix1/res/清空数据.png"), QStringLiteral("清空文本框"), this);
m_pActQuit = new QAction(QIcon(":/new/prefix1/res/退出.png"), QStringLiteral("退出"), this);
ui->mainToolBar->addAction(m_pActStartListen);
ui->mainToolBar->addAction(m_pActStopListen);
ui->mainToolBar->addAction(m_pActClearText);
ui->mainToolBar->addSeparator();
ui->mainToolBar->addAction(m_pActQuit);
//界面布局
m_pCentralWidget = new QWidget(this);
m_pGridLayout = new QGridLayout(m_pCentralWidget);
m_pLabel1 = new QLabel(QStringLiteral("监听地址"), m_pCentralWidget); //父对象为新的widget
// label对象被析构了,所以不会在界面显示。label1需要作为成员变量才可显示或者用指针
// QLabel label1;
// label1.setText("监听地址");
m_pComBoxIP = new QComboBox(m_pCentralWidget);
// m_pComBoxIP->addItem("192.168.1.104"); // QComboBox设置默认项必须添加项
//必须先add项才能操作下面
// comBoxAddr->setCurrentIndex(0);
// comBoxAddr->setCurrentText("192.168.1.104");
m_pLabel2 = new QLabel(QStringLiteral("监听端口"), m_pCentralWidget);
m_pSpinBoxPort = new QSpinBox(m_pCentralWidget);
m_pSpinBoxPort->setMinimum(1);
m_pSpinBoxPort->setMaximum(65535); //端口范围1~65535
m_pLineEdit = new QLineEdit(m_pCentralWidget);
m_pBtnSend = new QPushButto
3583


&spm=1001.2101.3001.11974&articleId=128869597&d=1&t=3&u=ba5a38c2177c4244968b95ab9c2266a9)

被折叠的 条评论
为什么被折叠?



