用qt写一段代码实现两个上位机通过代理连接两个下位机,两个下位机收到命令后会发送的数据,发送的数据会在两台上位机上同时显示出来
时间: 2024-03-23 13:41:16 浏览: 174
下面是一个简单的 Qt 代码示例,用于实现两个上位机通过代理连接两个下位机,两个下位机收到命令后会发送的数据,发送的数据会在两台上位机上同时显示出来:
```cpp
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
class TcpProxy : public QObject
{
Q_OBJECT
public:
explicit TcpProxy(QObject *parent = nullptr);
signals:
public slots:
void onNewClientConnection();
void onClientDataReady();
void onServerDataReady();
private:
QTcpServer *m_server;
QTcpSocket *m_client1;
QTcpSocket *m_client2;
QTcpSocket *m_serverSocket;
};
TcpProxy::TcpProxy(QObject *parent) : QObject(parent)
{
m_server = new QTcpServer(this);
m_server->listen(QHostAddress::Any, 1234);
connect(m_server, SIGNAL(newConnection()), this, SLOT(onNewClientConnection()));
}
void TcpProxy::onNewClientConnection()
{
if (!m_client1)
{
m_client1 = m_server->nextPendingConnection();
connect(m_client1, SIGNAL(readyRead()), this, SLOT(onClientDataReady()));
qDebug() << "Client 1 connected";
}
else if (!m_client2)
{
m_client2 = m_server->nextPendingConnection();
connect(m_client2, SIGNAL(readyRead()), this, SLOT(onClientDataReady()));
qDebug() << "Client 2 connected";
}
if (m_client1 && m_client2 && !m_serverSocket)
{
m_serverSocket = new QTcpSocket(this);
connect(m_serverSocket, SIGNAL(readyRead()), this, SLOT(onServerDataReady()));
m_serverSocket->connectToHost("localhost", 4321); // replace with your down-level machine's IP address and port number
qDebug() << "Server connected";
}
}
void TcpProxy::onClientDataReady()
{
QTcpSocket *senderSocket = qobject_cast<QTcpSocket*>(sender());
QTcpSocket *destSocket = (senderSocket == m_client1) ? m_client2 : m_client1;
QByteArray data = senderSocket->readAll();
destSocket->write(data);
if (m_serverSocket)
{
m_serverSocket->write(data);
}
}
void TcpProxy::onServerDataReady()
{
QByteArray data = m_serverSocket->readAll();
if (m_client1)
{
m_client1->write(data);
}
if (m_client2)
{
m_client2->write(data);
}
}
class TcpClient : public QObject
{
Q_OBJECT
public:
TcpClient(QObject *parent = nullptr);
signals:
public slots:
void onConnected();
void onDataReady();
private:
QTcpSocket *m_socket;
};
TcpClient::TcpClient(QObject *parent) : QObject(parent)
{
m_socket = new QTcpSocket(this);
connect(m_socket, SIGNAL(connected()), this, SLOT(onConnected()));
connect(m_socket, SIGNAL(readyRead()), this, SLOT(onDataReady()));
m_socket->connectToHost("localhost", 1234); // replace with your proxy IP address and port number
}
void TcpClient::onConnected()
{
qDebug() << "Connected to proxy";
}
void TcpClient::onDataReady()
{
QByteArray data = m_socket->readAll();
qDebug() << "Received data: " << data;
m_socket->write(data); // echo back the data
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TcpProxy tcpProxy;
TcpClient tcpClient;
return a.exec();
}
```
这段代码实现了一个 TCP 代理程序 `TcpProxy` 和一个 TCP 客户端程序 `TcpClient`,两个上位机分别运行一个客户端程序,通过代理程序连接到两个下位机。当下位机发送数据时,代理程序会将数据转发到两个上位机上,同时上位机也可以通过代理程序向下位机发送数据。
阅读全文