1.UDP通信
//UDP
{
Parameterflag=1;
this->udpSocket=new QUdpSocket(this);
bool ok = udpSocket->bind(QHostAddress::Any, 8088); // 绑定到所有可用的网络接口上的12345端口
if (!ok) {
// 处理绑定失败的情况
qDebug()<<"bind err";
}
connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
this->timer=new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::sendDatagram);
timer->start(1000);
}
相对应的信号与槽函数连接,使用定时器进行不同时连接;
//UDP 发送连接对应地址和端口号
void MainWindow::sendDatagram()
{
Parameterflag=1;
QByteArray datagram = "Hello, UDP!";
QHostAddress receiver("192.168.52.1"); // 目标地址
quint16 receiverPort = 9999; // 目标端口
udpSocket->writeDatagram(datagram, receiver, receiverPort);
qDebug() << "Sent datagram:" << datagram << "to" << receiver.toString() << ":" << receiverPort;
}
接收信息打印连接槽函数
cpp
void MainWindow::readPendingDatagrams()
{
Parameterflag=1;
// qDebug() <<"qerrttip";
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(int(udpSocket->pendingDatagramSize()));
QHostAddress sender;
quint16 senderPort;
// data:接收到发送端的 功能码。
// maxSize:功能码长度
// sender(可选):发送方的IP地址。
// senderPort(可选):发送方的端口号。
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug() << "Received datagram:" << datagram << "from" << sender.toString() << ":" << senderPort;
}
}
2. TCP服务器端连接
cpp
//TCP服务器
// {
// tcpServer=new QTcpServer(this);
// connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
// if (!tcpServer->listen(QHostAddress::Any, 8088)) {
// qDebug() << "Server could not start!";
// } else {
// qDebug() << "Server started on port 8088!";
// }
// }
创建对象成功,与其收发信息对应函数
cpp
//TCP SERVER
void MainWindow::onNewConnection()
{
Parameterflag=2;
//监听一个或多个端口
QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
connect(clientSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead_server);
connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater);
}
void MainWindow::onReadyRead_server()
{
Parameterflag=2;
QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
QByteArray data = clientSocket->readAll();
qDebug() << "Received from client:" << data;
// Echo the data back to the client
QString response = "Echo: " + QString::fromUtf8(data);
clientSocket->write(response.toUtf8());
}
3. TCP 客户端连接服务器端
cpp
//TCP客户端
{
// Parameterflag=3;
// this->tcpSocket=new QTcpSocket(this);
// connect(tcpSocket, &QTcpSocket::connected, this, &MainWindow::onConnected);
// connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);
// // Try to connect to the server
// tcpSocket->connectToHost("192.168.52.1", 8088);
// // Optionally, set a timeout for the connection attempt
// QTimer::singleShot(500, this, &MainWindow::onConnectionTimeout);
}
连接对应收发信息函数
cpp
void MainWindow::onConnected()
{
Parameterflag=3;
qDebug() << "Connected to server!";
// Send some data to the server
QByteArray data = "Hello, server!";
tcpSocket->write(data);
}
void MainWindow::onReadyRead()
{
Parameterflag=3;
QByteArray data = tcpSocket->readAll();
qDebug() << "Received from server:" << data;
// Optionally, close the connection after receiving a response
// tcpSocket->close();
// QCoreApplication::quit(); // If you want to quit the application after receiving the response
}
void MainWindow::onConnectionTimeout()
{
Parameterflag=3;
if (!tcpSocket->state() == QAbstractSocket::ConnectedState) {
qDebug() << "Connection timed out!";
tcpSocket->deleteLater();
QCoreApplication::quit(); // Or handle the timeout as needed
}
}
4.在QT中使用下拉框进行对应TCP客户端与服务器端,UDP切换连接
cpp
//下拉框发生切换槽函数
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
// QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
if(index==0)
{
qDebug()<<"UDP";
// Parameterflag=1;
UDPSocketFunction(8088);
}else if(index==1)
{
qDebug()<<"TCP Server";
// Parameterflag=2;
TCPserverFunction(8088);
}else if(index==2)
{
qDebug()<<"TCP Client";
// Parameterflag=3;
TCPClietnFunction(8088);
}
}
切换不同的通信协议对应将其连接的信号断开,将对象置空,创建对应通信模式连接
(1)UDP 切换函数
cpp
void MainWindow::UDPSocketFunction(int udpportnumber)
{
if(Parameterflag==2)
{
QTcpServer *tcpServer = this->tcpServer; // 之前创建的QTcpServer指针
if (tcpServer) {
// 停止监听新的连接
tcpServer->close();
// 断开信号和槽连接
disconnect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
// 释放并删除tcpServer对象(通过new分配的)
tcpServer->deleteLater();
this->tcpServer = nullptr; // 将指针设置为nullptr,以避免悬挂指针
}
}else if(Parameterflag==3)
{
if (this->tcpSocket->state() == QAbstractSocket::ConnectedState) {
// QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
tcpSocket->deleteLater(); // Clean up TCP socket
tcpSocket = nullptr; // Set pointer to nullptr to avoid dangling pointer
}
}
// UDP相关代码
{
QUdpSocket *udpSocket = new QUdpSocket(this); // 创建QUdpSocket对象
// 绑定到所有可用的网络接口上的指定端口
bool ok = udpSocket->bind(QHostAddress::Any, udpportnumber);
if (!ok) {
// 处理绑定失败的情况
qDebug()<<"bind err";
// 处理绑定失败的情况(删除udpSocket对象)
udpSocket->deleteLater();
}else{
connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
this->udpSocket = udpSocket;
this->timer=new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::sendDatagram);
timer->start(1000);
}
}
}
(2)TCP 服务器切换函数
cpp
void MainWindow::TCPserverFunction(int portnumber)
{
if (this->timer->isActive()) this->timer->stop();
qDebug()<<"Parameterflag"<<Parameterflag;
if(Parameterflag==1)
{
// UDP相关代码(之前已经存在)
QUdpSocket *udpSocket = this->udpSocket; // 之前创建的QUdpSocket指针
if (udpSocket) {
// 断开信号和槽连接
disconnect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
// 其他可能的清理工作...
// 删除udpSocket对象(如果它是通过new分配的)
udpSocket->deleteLater();
this->udpSocket = nullptr; // 将指针设置为nullptr,以避免悬挂指针
}
}else if(Parameterflag==3)
{
if (this->tcpSocket->state() == QAbstractSocket::ConnectedState) {
// QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
tcpSocket->disconnectFromHost(); // Clean up TCP socket
tcpSocket = nullptr; // Set pointer to nullptr to avoid dangling pointer
}
}
// TCP相关代码
QTcpServer *tcpServer = new QTcpServer(this); // 创建QTcpSocket对象
connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
if (!tcpServer->listen(QHostAddress::Any, portnumber)) {
qDebug() << "Server could not start!";
} else {
qDebug() << "Server started on port portnumber!";
this->tcpServer = tcpServer;
}
}
(3)TCP 客户端切换函数
cpp
void MainWindow::TCPClietnFunction(int tcpClietnportnumber)
{
if (this->timer->isActive()) this->timer->stop();
if(Parameterflag==1)
{
// UDP相关代码(之前已经存在)
QUdpSocket *udpSocket = this->udpSocket; // 之前创建的QUdpSocket指针
if (udpSocket) {
// 断开信号和槽连接
disconnect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
// 其他可能的清理工作...
// 删除udpSocket对象(如果它是通过new分配的)
udpSocket->deleteLater();
this->udpSocket = nullptr; // 将指针设置为nullptr,以避免悬挂指针
}
}else if(Parameterflag==2)
{
QTcpServer *tcpServer = this->tcpServer; // 之前创建的QTcpServer指针
if (tcpServer) {
// 停止监听新的连接
tcpServer->close();
// 断开信号和槽连接
disconnect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
// 释放并删除tcpServer对象(通过new分配的)
tcpServer->deleteLater();
this->tcpServer = nullptr; // 将指针设置为nullptr,以避免悬挂指针
}
}
//TCP Clietn
QTcpSocket *tcpSocket=new QTcpSocket(this);
connect(tcpSocket, &QTcpSocket::connected, this, &MainWindow::onConnected);
connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);
// Try to connect to the server
tcpSocket->connectToHost("192.168.52.1", tcpClietnportnumber);
// Optionally, set a timeout for the connection attempt
QTimer::singleShot(500, this, &MainWindow::onConnectionTimeout);
this->tcpSocket=tcpSocket;
}