通过qt写一个socket代理层实现两个上位机同时连接同一个下位机,并能够实现上位机与下位机的数据交互
时间: 2024-03-11 19:47:37 浏览: 115
下面是一个使用Qt实现的socket代理层的示例代码,可以实现两个上位机同时连接同一个下位机,并能够实现上位机与下位机的数据交互:
```cpp
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QList>
class ProxyServer : public QTcpServer
{
Q_OBJECT
public:
ProxyServer(QObject *parent = nullptr) : QTcpServer(parent) {}
protected:
void incomingConnection(qintptr socketDescriptor) override
{
// 创建客户端socket
QTcpSocket *clientSocket = new QTcpSocket(this);
// 连接下位机
clientSocket->connectToHost("192.168.1.100", 1234);
// 创建代理
Proxy *proxy = new Proxy(this);
proxy->setClientSocket(clientSocket);
proxy->setProxySocket(new QTcpSocket(this));
// 添加到列表中
m_proxies.append(proxy);
// 连接代理socket
proxy->proxySocket()->setSocketDescriptor(socketDescriptor);
connect(proxy->proxySocket(), &QTcpSocket::readyRead, proxy, &Proxy::onReadyRead);
connect(proxy->proxySocket(), &QTcpSocket::disconnected, proxy, &Proxy::disconnectFromHost);
}
private:
QList<Proxy*> m_proxies;
};
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QObject *parent = nullptr) : QObject(parent) {}
void setClientSocket(QTcpSocket *clientSocket) { m_clientSocket = clientSocket; }
void setProxySocket(QTcpSocket *proxySocket) { m_proxySocket = proxySocket; }
QTcpSocket* proxySocket() const { return m_proxySocket; }
public slots:
void onReadyRead()
{
// 转发数据
QByteArray data = m_proxySocket->readAll();
m_clientSocket->write(data);
}
void disconnectFromHost()
{
// 断开连接
m_clientSocket->disconnectFromHost();
m_proxySocket->disconnectFromHost();
deleteLater();
}
private:
QTcpSocket *m_clientSocket;
QTcpSocket *m_proxySocket;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ProxyServer server;
if (!server.listen(QHostAddress::Any, 5678)) {
qCritical() << "Failed to start server:" << server.errorString();
return -1;
}
qDebug() << "Server started on port" << server.serverPort();
return a.exec();
}
#include "main.moc"
```
在上面的示例中,我们创建了一个ProxyServer类,继承自QTcpServer。在incomingConnection()函数中,我们创建了一个QTcpSocket对象,连接下位机,并创建一个Proxy对象代表代理。然后将Proxy对象添加到列表中,并连接代理socket的readyRead()和disconnected()信号到代理对象的onReadyRead()和disconnectFromHost()槽函数。
在Proxy类中,我们可以通过setClientSocket()和setProxySocket()函数设置客户端socket和代理socket。在onReadyRead()槽函数中,我们将代理socket的数据转发给客户端socket,实现了数据交互。在disconnectFromHost()槽函数中,我们断开连接,并删除代理对象。
最后,在main()函数中,我们创建了一个ProxyServer对象并监听5678端口。如果启动失败,将输出错误信息。如果成功启动,则输出端口号。
阅读全文