Comunicación de socket de red QTcpSocket

Darse cuenta del lado del servidor y del lado del cliente, el método de recepción adopta el método de recepción de ranura, y los documentos oficiales pueden ser vistos por F1 F2 durante el proceso

Servidor

Nueva clase, seleccione la clase base

Archivo fuente

archivo .h

#ifndef SOCKET_H
#define SOCKET_H


#include <QObject>
#include <qtcpserver.h>
#include <qtcpsocket.h>


class socket : public QObject
{
    Q_OBJECT
public:
    explicit socket(int port,QObject *parent = nullptr);


    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;
    void WriteData(QByteArray bytes);
public slots:
    void acceptConnection();
    void readData();
};


#endif // SOCKET_H

archivo .cpp

#include "socket.h"


socket::socket(int port, QObject *parent) : QObject(parent)
{
    tcpServer = new QTcpServer();
    tcpServer->listen(QHostAddress::Any,port);
    tcpSocket = nullptr;
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
}


void socket::acceptConnection(){
    qDebug()<<"connect";
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readData()));
    connect(tcpSocket, &QAbstractSocket::disconnected,tcpSocket, &QObject::deleteLater);
}


void socket::readData(){
    QByteArray bytes = tcpSocket->readAll();
    qDebug()<<bytes;
}


void socket::WriteData(QByteArray bytes){
    if(tcpSocket->isOpen()){
        tcpSocket->write(bytes);
    }
}

Puntos a tener en cuenta

  1. Es necesario citar dos archivos de encabezado qtcpserver.hy qtcpsocket.h, dos de los cuales contienen el servidor y el cliente
  2. El servidor está esperando la conexión, y hay una conexión que necesita usar socket para comunicarse, dentro de la señal readyData
  3. Cuando se inicializa el uso en la interfaz principal, socket * m = new socket (6789);

Cliente

Cree una nueva clase, seleccione la clase base, lo mismo que el servidor

Archivo fuente

.cpp

#include "socket.h"
#include "servo.h"
#include "vrep.h"


socket::socket(QObject *parent) : QObject(parent)
{
    tcpSocket = new QTcpSocket(parent);
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readData()));
}


void socket::ConnectServer(const QString &hostName,int port){
    tcpSocket->connectToHost(hostName,port);
}
void socket::readData(){
    QByteArray bytes = tcpSocket->readAll();
    qDebug()<<bytes;
}


void socket::WriteData(QByteArray bytes){
    if(tcpSocket!=nullptr && tcpSocket->isOpen()){
        tcpSocket->write(bytes);
    }
    else
        qDebug()<<"disconnection";
}

.h

#ifndef SOCKET_H
#define SOCKET_H


#include <QObject>
#include <qtcpserver.h>
#include <qtcpsocket.h>

class socket : public QObject
{
    Q_OBJECT
public:
    explicit socket(QObject *parent = nullptr);


    QByteArray m_bytes;
    QTcpSocket *tcpSocket;


    void ConnectServer(const QString &hostName,int port);
    void WriteData(QByteArray bytes);
    uint8_t getCheck(QByteArray bytes);
private:
    int receiveLength;
public slots:
    void readData();
};

#endif // SOCKET_H

Nota

La instanciación debe estar en un hilo de interfaz de usuario accesible

m_socket = nuevo socket (este);

Supongo que te gusta

Origin blog.csdn.net/shaynerain/article/details/106130986
Recomendado
Clasificación