Using TCP server and client in Qt

Using TCP server and client in Qt

TCP (Transmission Control Protocol) is a reliable, highly optimized Internet communication protocol that is widely used in various network applications. In this blog, we will introduce how to use TCP server and client in Qt.

Create a TCP server using Qt

To create a TCP server using Qt, you need to complete the following steps:

Step 1: Create QTcpServer object

QTcpServer *server = new QTcpServer(this);

Step 2: Listen for connection requests

Before you start listening, you need to use the listen() method to specify the service port number and listen for connection requests from a specific IP address.

if (!server->listen(QHostAddress::Any, 12345))
{
    
    
    qDebug() << "Failed to start server";
    return;
}

Step 3: Handle new connection requests

Whenever a new connection request arrives at the server, QTcpServer will notify you by emitting the newConnection() signal. You can use the accept() method to accept the connection and create a new QTcpSocket object to send and receive messages.

void MyTcpServer::newConnection()
{
    
    
    QTcpSocket *socket = server->nextPendingConnection();
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}

void MyTcpServer::readData()
{
    
    
    QTcpSocket *socket = static_cast<QTcpSocket *>(sender());
    QByteArray data = socket->readAll();
    // 处理接收到的数据
}

Step 4: Send data

Use QTcpSocket's write() method to send your data to the connected client.

socket->write("Hello world");

Create TCP client using Qt

To create a TCP client using Qt, you need to complete the following steps:

Step 1: Create QTcpSocket object

QTcpSocket *m_socket = new QTcpSocket(this);

Step 2: Connect to the server

Use the connectToHost() method to connect the socket to the target host and port. After the connection is successful, QTcpSocket will send the connected() signal.

m_socket->connectToHost(QHostAddress("127.0.0.1"), 12345);

Step 3: Send and receive data

Use the write() method to send data to the server and process the received data through the readyRead() signal.

void MyTcpClient::sendData(QString data)
{
    
    
    m_socket->write(data.toUtf8().constData());
}

void MyTcpClient::readData()
{
    
    
    QString data = m_socket->readAll();
    // 处理接收到的数据
}

Summarize

Using TCP servers and clients in Qt is a reliable and efficient method for network communication. The QTcpServer and QTcpSocket classes provide an object-oriented solution that allows you to easily develop various types of network applications.

However, be aware of delays and exceptions that can occur for a variety of reasons (such as network outages, remote hosts closing connections, etc.) and be sure to handle these situations in your code to ensure application stability.

Guess you like

Origin blog.csdn.net/qq_25549309/article/details/131698321