> 文章列表 > QT中实现TCP和UDP通信

QT中实现TCP和UDP通信

QT中实现TCP和UDP通信

TCP通信

QT中实现TCP通信主要用到了以下类:QTcpServer、QTcpSocket、QHostAddress等;

TCP服务端程序编写

  • 使用QTcpServer来创建一个TCP服务器,在新的连接建立时,将新建立连接的socket添加到列表中,以便发送数据
  • 同时监听在指定的IP地址和端口上,并在有新的客户端连接上来时进行处理;

示例代码:

#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>void TcpServer::startServer()
{tcpServer = new QTcpServer(this);connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClientConnection()));if (!tcpServer->listen(QHostAddress::Any, 1234)){qDebug() << "Unable to start the server: " << tcpServer->errorString();return;}qDebug() << "Listening on " << QHostAddress::Any << ":" << "1234";
}void TcpServer::newClientConnection()
{while (tcpServer->hasPendingConnections()) {QTcpSocket *client = tcpServer->nextPendingConnection();clients.push_back(client);QObject::connect(client, SIGNAL(readyRead()), this, SLOT(readData()));QObject::connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));}
}void TcpServer::readData() 
{QTcpSocket *sender = static_cast<QTcpSocket*>(QObject::sender());QByteArray data = sender->readAll();qDebug() << "Received: " << data;
}void TcpServer::clientDisconnected() 
{QTcpSocket *sender = static_cast<QTcpSocket*>(QObject::sender());clients.removeOne(sender);sender->deleteLater();
}

TCP客户端程序编写

  • 使用QTcpSocket来创建一个TCP客户端,连接到服务器并发送数据;

示例代码:

#include <QTcpSocket>
#include <QDebug>void TcpClient::connectToServer(QString ipAddress, int port)
{socket = new QTcpSocket(this);connect(socket, SIGNAL(connected()), this, SLOT(onConnected()));connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));socket->connectToHost(ipAddress, port);
}void TcpClient::sendData(QByteArray data)
{if (socket && socket->state() == QAbstractSocket::ConnectedState)socket->write(data);
}void TcpClient::onConnected()
{qDebug() << "Connected!";
}void TcpClient::onDisconnected()
{qDebug() << "Disconnected!";
}void TcpClient::onError(QAbstractSocket::SocketError error)
{qDebug() << "Error: " << socket->errorString();
}void TcpClient::onReadyRead()
{qDebug() << "Received: " << socket->readAll();
}

TCP客户端与TCP服务端测试

下面是使用上述TCP客户端和TCP服务端进行通信的示例代码:

//TCP服务端
TcpServer server;
server.startServer();//TCP客户端
TcpClient client;
client.connectToServer("127.0.0.1", 1234);//发送数据
client.sendData("Hello from client!");

UDP通信

QT中实现UDP通信主要用到了以下类:QUdpSocket、QHostAddress等;

UDP单播与广播程序编写

示例代码:

该示例中,我们使用QUdpSocket创建一个名为socket的socket对象,并将其绑定到指定IP地址和端口号,在接收数据时,使用readDatagram函数读取数据并输出到控制台;

#include <QUdpSocket>void UdpCommunicator::bindSocket()
{socket = new QUdpSocket(this);socket->bind(QHostAddress::Any, 1234);connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}void UdpCommunicator::sendData(QByteArray data, QString ipAddress)
{QHostAddress receiverAddress(ipAddress);socket->writeDatagram(data, receiverAddress, 1234);
}void UdpCommunicator::readData()
{while (socket->hasPendingDatagrams()) {QByteArray data;data.resize(socket->pendingDatagramSize());QHostAddress sender;quint16 senderPort;socket->readDatagram(data.data(), data.size(), &sender, &senderPort);qDebug() << "Received Data: " << data;}
}

使用上述UDP单播程序进行测试很简单,只需向指定的IP地址发送数据即可(请确保该计算机正在运行此程序):

UdpCommunicator udpComm;
udpComm.bindSocket();
udpComm.sendData("Hello from client!", "127.0.0.1");

为了演示UDP广播,我们可以将上述程序进行适当的修改:

void UdpCommunicator::bindSocket()
{socket = new QUdpSocket(this);connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));//Broadcastingsocket->bind(QHostAddress::AnyIPv4, 1234, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);socket->joinMulticastGroup(QHostAddress("239.255.43.21"));
}void UdpCommunicator::sendData(QByteArray data)
{QHostAddress multicastAddress("239.255.43.21");socket->writeDatagram(data, multicastAddress, 1234);
}

此时,我们使用广播地址发送数据即可:

UdpCommunicator udpComm;
udpComm.bindSocket();
udpComm.sendData("Hello from client!");