Qt 中的网络编程(QTcpSocket Class 客户端类)

 回顾c语言中的网络tcp编程:

Header:#include <QTcpSocket> 头文件
qmake:QT += network     //模块
Inherits:QAbstractSocket    //父类
Inherited By:QSctpSocket and QSslSocket   //派生类

注意:使用QTcpSocket 必须先在 .pro文件中加入模块 network

函数接口:

//构造函数
QTcpSocket(QObject *parent = nullptr)

//链接服务器 直接填写 IP+端口 即可链接
connectToHost(const QString &, quint16 , QIODevice::OpenMode ,QAbstractSocket::NetworkLayerProtocol )

例子:
    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
       //1.创建一个客户端的通信对象
       QTcpSocket *scoket= new QTcpSocket(this);

       //2.链接服务器
       scoket->connectToHost("192.168.25.32",1000);

       //3.发送消息
       scoket->write("hello");

       //4.关联可读信号
       connect(scoket,SIGNAL(readyRead),this,SLOT(read_data()));
}

数据的收发:
    write(const char *, qint64 )  //发送 qint64 大的数据 
    write(const char *)          //直接发送字符数据 
    write(const QByteArray &)   //发生QByteArray 类型的数据 

//数据的接收
    qint64 read(char *, qint64 )  //读取 qint64 大的数据到  char * 地址 上 
    QByteArray  read(qint64 ) //读取 qint64 大的数据 并返回 
    QByteArray  readAll() //读取所有数据

也可以自定义窗体发送与接收:

点击发送转到槽:

//转到发送槽
void MainWindow::on_pushButton_clicked()
{
   //toPlainText()获取输入框的内容,返回 QString
   QString msg =  ui->textEdit->toPlainText();

   //数据发送write(const QByteArray &),
    scoket->write(msg.toUtf8());
}

注意:QString 转 QByteArray 加 toUtf8()   ,由于使用toUtf8编码格式,所有消息不能发中文,会出现乱码

而接收数据就要关联可读信号(也就是信号与槽)

        查看父类接口,点击Singals即可找到

关联可读信号最后,即可编写槽函数

void MainWindow::read_data()
{
    QString msg = scoket->readAll();
    ui->textBrowser->setPlainText(msg);
}

实例代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

//添加网络头文件
#include <QTcpSocket>

QTcpSocket  *socket;

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

    //1.创建一个客户端的通信对象
    socket =  new QTcpSocket(this);


    //2.链接服务器
    socket->connectToHost("192.168.25.2",1000);

    //3.数据的发送
    socket->write("hello");

    //4.关联可读信号
    connect(socket,SIGNAL(readyRead()),this,SLOT(read_date()));


}

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


void MainWindow::on_pushButton_clicked()
{
      QString msg  = ui->textEdit->toPlainText();


      socket->write(msg.toUtf8());
}

void MainWindow::read_date()
{
     QString msg  = socket->readAll();

     ui->textBrowser->setPlainText(msg);
}

//练习:实现客户端与调试助手的双向通信

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,这是一个简单的Qt网络编程计算器的代码示例: ```cpp #include <QtWidgets> #include <QtNetwork> class Calculator : public QWidget { Q_OBJECT public: Calculator(QWidget *parent = nullptr); private slots: void requestNewConnection(); void readClientData(); void sendResult(); private: QTcpServer *tcpServer; QTcpSocket *clientSocket; QTextEdit *display; quint16 blockSize; QString currentOperation; double currentResult; }; Calculator::Calculator(QWidget *parent) : QWidget(parent), tcpServer(new QTcpServer(this)), clientSocket(nullptr), display(new QTextEdit(this)), blockSize(0), currentOperation(""), currentResult(0.0) { if (!tcpServer->listen(QHostAddress::Any, 1234)) { QMessageBox::critical(this, tr("Error"), tr("Unable to start the server: %1.").arg(tcpServer->errorString())); close(); return; } connect(tcpServer, &QTcpServer::newConnection, this, &Calculator::requestNewConnection); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(display); } void Calculator::requestNewConnection() { if (clientSocket) { clientSocket->disconnectFromHost(); clientSocket->deleteLater(); } clientSocket = tcpServer->nextPendingConnection(); connect(clientSocket, &QTcpSocket::readyRead, this, &Calculator::readClientData); } void Calculator::readClientData() { QDataStream in(clientSocket); in.setVersion(QDataStream::Qt_5_15); if (blockSize == 0) { if (clientSocket->bytesAvailable() < static_cast<int>(sizeof(quint16))) return; in >> blockSize; } if (clientSocket->bytesAvailable() < blockSize) return; QString operation; in >> operation; if (operation == "clear") { currentResult = 0.0; currentOperation = ""; display->setText(""); } else if (operation == "+" || operation == "-" || operation == "*" || operation == "/") { currentOperation = operation; currentResult = display->toPlainText().toDouble(); display->setText(""); } else if (operation == "=") { double operand = display->toPlainText().toDouble(); if (currentOperation == "+") currentResult += operand; else if (currentOperation == "-") currentResult -= operand; else if (currentOperation == "*") currentResult *= operand; else if (currentOperation == "/") currentResult /= operand; display->setText(QString::number(currentResult)); } sendResult(); } void Calculator::sendResult() { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_15); out << static_cast<quint16>(0); out << display->toPlainText(); out.device()->seek(0); out << static_cast<quint16>(block.size() - sizeof(quint16)); clientSocket->write(block); blockSize = 0; } int main(int argc, char *argv[]) { QApplication app(argc, argv); Calculator calculator; calculator.show(); return app.exec(); } ``` 这个计算器使用TCP协议进行通信,监听端口号为1234。当客户端连接到服务器时,服务器会接收客户端发送的数据,并根据数据进行计算,然后将计算结果发送回客户端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这仅仅是一个很长的昵称而已

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值