当前位置:网站首页>QTcpServer. QTcpSocket. Differences between qudpsockets

QTcpServer. QTcpSocket. Differences between qudpsockets

2022-06-13 10:24:00 Just a little bit

1. QTcpServer

Gu Mingsi means , Just do it Tcp For server ,Qt It's all encapsulated , Just call it directly

Usage method :new An object , Binding address and port , Then through the signal and slot , Handle incoming connections

    m_server = new QTcpServer();
    // Listening address and port number 
    m_server->listen(QHostAddress::Any, 8888);
    connect(m_server, &QTcpServer::newConnection, this, &myServer::handleSocket);

Processing function

void myServer::handleSocket()
{
    QTcpSocket* socket = m_server->nextPendingConnection();
    ......
}
 Write data through write that will do 

Read data through readAll

QByteArray messageByte =  socket->readAll();

2. QTcpSocket The connection is reliable , It's one-on-one

QTcpSocket The connection is reliable , It's one-on-one

Usage method :

1.new One QTcpSocket

m_Tcpsocket = new QTcpSocket();

2. Connect to the specified ip And port

m_Tcpsocket->connectToHost("127.0.0.1", 8888);

3. Just wait for the connection

if(m_Tcpsocket->waitForConnected(3000))
{
    ui->textBrowser->append(" Successfully connected to server !");
    connect(m_Tcpsocket, &QTcpSocket::readyRead,[=]()
    {
        ui->textBrowser->append(m_Tcpsocket->readAll());
    });
    connect(m_UdpSocket, &QUdpSocket::readyRead, this, &Dialog::receive);
}

3. QUcpSocket

QUcpSocket Your connection is unreliable , It is one to many or many to many , It's very efficient , The packet loss rate is also high

Usage method :new One QUdpSocket, If you just write data to send , If you don't read the data , No use bind() Method to bind the address and port

m_udpSocket = new QUdpSocket();
 Binding port , When reading data, you need to specify the port , And address 
    m_UdpSocket->bind(5555, QUdpSocket::ShareAddress);

When writing data , Designated port , Generally, it is sent to the designated port number by broadcasting

m_udpSocket->writeDatagram(message.toLatin1().data(), message.size(),
                                  QHostAddress::Broadcast, 5555);

When reading data , Read the data sent by binding the port number , Can't take QTcpSocket How to read data (readAll) Reading data , You can't read it

Use the following methods :

connect(m_UdpSocket, &QUdpSocket::readyRead, this, &Dialog::receive);

void Dialog::receive()
{


    while(m_UdpSocket->hasPendingDatagrams())    // Judge udpSocket Is there any data waiting to be read 
    {
        QByteArray datagram;
        datagram.resize(m_UdpSocket->pendingDatagramSize());// Resize 
        m_UdpSocket->readDatagram(datagram.data(), datagram.size());// Read the first datagram The length of 
        QString msg=datagram.data();
        ui->textBrowser->append(msg);
    }

}

原网站

版权声明
本文为[Just a little bit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206131006091253.html