QT开发之TCP协议

这篇文章用一个简单的例子实现客户端和服务端之间的通信,用C语言写网络编程相关的代码相对复杂了,还是C++的面向对象思想,对类的封装和继承做的很好.


client.h

#ifndef CLIENT_H
#define CLIENT_H

#include <QDialog>
#include <QAbstractSocket>

class QTcpSocket;

namespace Ui {
class Client;
}

class Client : public QDialog
{
    Q_OBJECT
    
public:
    explicit Client(QWidget *parent = 0);
    ~Client();
    
private:
    Ui::Client *ui;
    QTcpSocket *tcpSocket;
    QString message;
    quint16 blockSize;

private slots:
    void newConnect();
    void readMessage();
    void displayError(QAbstractSocket::SocketError);
    void on_connectButton_clicked();
};

#endif // CLIENT_H

client.cpp

#include "client.h"
#include "ui_client.h"
#include <QtNetwork>

Client::Client(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
}

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

void Client::newConnect()
{

    blockSize = 0;

    tcpSocket->abort();
    tcpSocket->connectToHost(ui->hostLineEdit->text(),
                             ui->portLineEdit->text().toInt());
}

void Client::readMessage()
{
    QDataStream in(tcpSocket);

    in.setVersion(QDataStream::Qt_4_4);

    if (blockSize == 0) {

        if(tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return;
        in >> blockSize;
    }

    if(tcpSocket->bytesAvailable() < blockSize) return;

    in >> message;

    qDebug() << message;
    ui->messageLabel->setText(message);
}

void Client::displayError(QAbstractSocket::SocketError)
{
    qDebug() << tcpSocket->errorString();
}


void Client::on_connectButton_clicked()
{
    newConnect();
}

server.h

#ifndef SERVER_H
#define SERVER_H

#include <QDialog>

namespace Ui {
class Server;
}

class QTcpServer;

class Server : public QDialog
{
    Q_OBJECT
    
public:
    explicit Server(QWidget *parent = 0);
    ~Server();
    
private:
    Ui::Server *ui;
    QTcpServer *tcpServer;

private slots:
    void sendMessage();
};

#endif // SERVER_H

server.cpp

#include "server.h"
#include "ui_server.h"
#include <QtNetwork>

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

    tcpServer = new QTcpServer(this);
    if(!tcpServer->listen(QHostAddress::LocalHost,8080))
    {
        qDebug() << tcpServer->errorString();
        close();
    }
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
}

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

void Server::sendMessage()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_4_4);
    out << (quint16)0;
    out << tr("Linux_Google CSDN");
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    /* 获取连接的客户端套接字 */
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));
    clientConnection->write(block);  /* 发送数据给客户端 */
    clientConnection->disconnectFromHost();

    ui->label->setText("send message successful!!!");

}

界面效果如下:



                                                                                                                            文章出自:Linux_Google

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页