Qt下Tcp套接字(socket)通信的整个流程

本文详细介绍了在QT环境中进行TCP网络编程的过程,包括在.pro文件中添加QTcpServer和QTcpSocket模块,服务器端如何监听和接收连接,以及客户端如何连接服务器并进行数据收发。示例代码展示了服务器和客户端的完整实现。
摘要由CSDN通过智能技术生成

一、QT如果要进行网络编程首先需要在.pro中添加如下代码:

QT += network

二、QT下的TCP通信过程

Qt中提供的所有的Socket类都是非阻赛的
Qt中常用的用于socket通信的套接字类
        QTcpServer
用于TCP/IP通信,作为服务器端套接字使用
        QTcpSocket
用于TCP/IP通信,作为客户端套接字使用。
        QUdpSocket
用于UDP通信,服务器,客户端均使用此套接字

三、描述Qt下Tcp通信的整个流程 

服务器端:

1. 创建用于监听的套接字 

     //监听套接字
     tcpServer = new QTcpServer(this);


2. 给套接字设置监听 

    tcpServer->listen(QHostAddress::Any,8888);
    setWindowTitle("服务器:8888");


3. 如果有连接到来, 监听的套接字会发出信号newConnected 
4. 接收连接, 通过nextPendingConnection()函数, 返回一个QTcpSocket类型的套接字对象(用于通信) 

    connect(tcpServer,&QTcpServer::newConnection,[=](){
        //取出建立好连接的套接字
        tcpSocket = tcpServer->nextPendingConnection();
    });


5. 使用用于通信的套接字对象通信 
(1). 发送数据: write 

    if(NULL == tcpSocket)
    {
        return;
    }
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    //给对方发送数据,使用套接字是tcpSocket
    tcpSocket->write(str.toUtf8().data());


(2). 接收数据: readAll/read  

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
            //从通信套接字中取出内容
            QByteArray array = tcpSocket->readAll();
            array = "客户端;" + array;
            ui->textEditRead->append(array);
        });

客户端:

1. 创建用于通信的套接字 

    tcpSocket = new QTcpSocket(this);
    setWindowTitle("客户端");


2. 连接服务器: connectToHost 

    //获取服务器IP和端口
    QString ip = ui->lineEditIP->text();
    qint16 port = ui->lineEditPort->text().toInt();

    //主动与服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ip),port);

    
    connect(tcpSocket,&QTcpSocket::connected,[=](){
        ui->textEditRead->setText("成功和服务器建立好连接");
    });


3. 连接成功与服务器通信 
(1).发送数据: write 

    //获取编辑框内容
    QString str = ui->textEditWrite->toPlainText();
    //发送数据
    tcpSocket->write(str.toUtf8().data());


(2).接收数据: readAll/read

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
       //获取对方发送的内容
        QByteArray array = tcpSocket->readAll();
        //追加到编辑区中
        array = "服务端:" + array;
        ui->textEditRead->append(array);
    });

四、完整代码

服务端:

 setverwidget.h

#ifndef SERVERWIDGET_H
#define SERVERWIDGET_H

#include <QWidget>
#include <QTcpServer> //监听套接字
#include  <QTcpSocket> //通信套接字

namespace Ui {
class ServerWidget;
}

class ServerWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ServerWidget(QWidget *parent = 0);
    ~ServerWidget();

private slots:
    void on_buttonSend_clicked();

    void on_pushButton_2_clicked();

private:
    Ui::ServerWidget *ui;

    QTcpServer *tcpServer;//监听套接字
    QTcpSocket *tcpSocket;//通信套接字
};

#endif // SERVERWIDGET_H

serverwidget.cpp

#include "serverwidget.h"
#include "ui_serverwidget.h"

ServerWidget::ServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerWidget)
{
    ui->setupUi(this);
    tcpServer = NULL;
    tcpSocket = NULL;

    //监听套接字
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8888);
    setWindowTitle("服务器:8888");
    connect(tcpServer,&QTcpServer::newConnection,[=](){
        //取出建立好连接的套接字
        tcpSocket = tcpServer->nextPendingConnection();

        //获取对方的IP和端口
        QString ip = tcpSocket->peerAddress().toString();
        qint16 port = tcpSocket->peerPort();
        QString temp = QString("[%1:%2]:连接成功").arg(ip).arg(port);

        ui->textEditRead->setText(temp);

        connect(tcpSocket,&QTcpSocket::readyRead,[=](){
            //从通信套接字中取出内容
            QByteArray array = tcpSocket->readAll();
            array = "客户端;" + array;
            ui->textEditRead->append(array);
        });
    });

}

ServerWidget::~ServerWidget()
{
    delete ui;
}

void ServerWidget::on_buttonSend_clicked()
{
    if(NULL == tcpSocket)
    {
        return;
    }
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    //给对方发送数据,使用套接字是tcpSocket
    tcpSocket->write(str.toUtf8().data());
    ui->textEditWrite->setText("");
}

void ServerWidget::on_pushButton_2_clicked()
{
    if(NULL == tcpSocket)
    {
        return;
    }
    //主动和客户端端口连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket = NULL;
}

客户端:

clientwidget.h

#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H

#include <QWidget>
#include <QTcpSocket>//通信套接字

namespace Ui {
class ClientWidget;
}

class ClientWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ClientWidget(QWidget *parent = 0);
    ~ClientWidget();

private slots:
    void on_buttonConnect_clicked();

    void on_buttonSend_clicked();

    void on_buttonClose_clicked();

private:
    Ui::ClientWidget *ui;

    QTcpSocket *tcpSocket;//通信套接字
};

#endif // CLIENTWIDGET_H

clientwidget.cpp

#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QHostAddress>

ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    tcpSocket = NULL;

    tcpSocket = new QTcpSocket(this);
    setWindowTitle("客户端");

    connect(tcpSocket,&QTcpSocket::connected,[=](){
        ui->textEditRead->setText("成功和服务器建立好连接");
    });

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
       //获取对方发送的内容
        QByteArray array = tcpSocket->readAll();
        //追加到编辑区中
        array = "服务端:" + array;
        ui->textEditRead->append(array);
    });
}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_buttonConnect_clicked()
{
    //获取服务器IP和端口
    QString ip = ui->lineEditIP->text();
    qint16 port = ui->lineEditPort->text().toInt();

    //主动与服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ip),port);
}

void ClientWidget::on_buttonSend_clicked()
{
    //获取编辑框内容
    QString str = ui->textEditWrite->toPlainText();
    //发送数据
    tcpSocket->write(str.toUtf8().data());
    ui->textEditWrite->setText("");
}

void ClientWidget::on_buttonClose_clicked()
{
    //主动和对方断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

  • 8
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt 中创建本地 IP 套接字可以使用 QTcpSocket 类。下面是一个简单的示例代码,演示如何创建一个本地 IP 套接字: ```cpp #include <QtNetwork/QTcpSocket> #include <QtNetwork/QHostAddress> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTcpSocket socket; socket.connectToHost(QHostAddress::LocalHost, 8080); return a.exec(); } ``` 在上面的示例中,我们首先包含了 `QTcpSocket` 和 `QHostAddress` 头文件。然后,我们创建了一个 `QTcpSocket` 对象并调用了 `connectToHost()` 函数来连接到本地 IP 地址和端口号为 8080 的主机。在实际应用中,你需要根据你的需求来更改本地 IP 地址和端口号。 需要注意的是,如果你希望创建一个本地服务器套接字,你需要使用 `QTcpServer` 类。在服务器端,你需要监听来自本地 IP 地址和端口号的连接请求。以下是一个简单的示例代码,演示如何创建一个本地服务器套接字: ```cpp #include <QtNetwork/QTcpServer> #include <QtNetwork/QHostAddress> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTcpServer server; server.listen(QHostAddress::LocalHost, 8080); return a.exec(); } ``` 在上面的示例中,我们首先包含了 `QTcpServer` 和 `QHostAddress` 头文件。然后,我们创建了一个 `QTcpServer` 对象并调用了 `listen()` 函数来监听来自本地 IP 地址和端口号为 8080 的连接请求。在实际应用中,你需要根据你的需求来更改本地 IP 地址和端口号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值