用qt写一段socket代理层的代码实现两个上位机同时连接两个下位机,并将两个下位机的数据呈现在上位机上
时间: 2024-03-12 20:47:36 浏览: 89
好的,我来给您提供一段示例代码,实现两个上位机同时连接两个下位机,并将两个下位机的数据呈现在上位机上。
```cpp
#include <QtNetwork>
#include <QObject>
class SocketProxy : public QObject
{
Q_OBJECT
public:
explicit SocketProxy(QObject *parent = nullptr);
~SocketProxy();
private slots:
void onFirstClientConnected();
void onSecondClientConnected();
void onFirstClientDisconnected();
void onSecondClientDisconnected();
void onFirstClientReadyRead();
void onSecondClientReadyRead();
private:
QTcpServer *m_server1;
QTcpServer *m_server2;
QTcpSocket *m_client1;
QTcpSocket *m_client2;
};
SocketProxy::SocketProxy(QObject *parent)
: QObject(parent)
, m_server1(new QTcpServer(this))
, m_server2(new QTcpServer(this))
, m_client1(nullptr)
, m_client2(nullptr)
{
connect(m_server1, &QTcpServer::newConnection, this, &SocketProxy::onFirstClientConnected);
connect(m_server2, &QTcpServer::newConnection, this, &SocketProxy::onSecondClientConnected);
if (!m_server1->listen(QHostAddress::Any, 8888)) {
qWarning() << "Failed to start server1:" << m_server1->errorString();
}
if (!m_server2->listen(QHostAddress::Any, 9999)) {
qWarning() << "Failed to start server2:" << m_server2->errorString();
}
}
SocketProxy::~SocketProxy()
{
m_server1->close();
m_server2->close();
}
void SocketProxy::onFirstClientConnected()
{
if (!m_client1) {
m_client1 = m_server1->nextPendingConnection();
connect(m_client1, &QTcpSocket::disconnected, this, &SocketProxy::onFirstClientDisconnected);
connect(m_client1, &QTcpSocket::readyRead, this, &SocketProxy::onFirstClientReadyRead);
}
}
void SocketProxy::onSecondClientConnected()
{
if (!m_client2) {
m_client2 = m_server2->nextPendingConnection();
connect(m_client2, &QTcpSocket::disconnected, this, &SocketProxy::onSecondClientDisconnected);
connect(m_client2, &QTcpSocket::readyRead, this, &SocketProxy::onSecondClientReadyRead);
}
}
void SocketProxy::onFirstClientDisconnected()
{
if (m_client1) {
m_client1->deleteLater();
m_client1 = nullptr;
}
}
void SocketProxy::onSecondClientDisconnected()
{
if (m_client2) {
m_client2->deleteLater();
m_client2 = nullptr;
}
}
void SocketProxy::onFirstClientReadyRead()
{
if (m_client2 && m_client2->state() == QTcpSocket::ConnectedState) {
QByteArray data = m_client1->readAll();
m_client2->write(data);
}
}
void SocketProxy::onSecondClientReadyRead()
{
if (m_client1 && m_client1->state() == QTcpSocket::ConnectedState) {
QByteArray data = m_client2->readAll();
m_client1->write(data);
}
}
```
这段代码实现了一个简单的Socket代理层,监听两个端口,等待两个上位机分别连接到这两个端口上。连接建立后,将两个下位机的数据流量分别转发到对应的上位机连接上。如果有任何一个连接断开,将会关闭整个Proxy服务。在具体使用时,您需要将该代理层代码嵌入到您的Qt应用程序中,并且将数据的呈现逻辑添加到`onFirstClientReadyRead()`和`onSecondClientReadyRead()`函数中。
阅读全文